0

pthread_t (as returned by pthread_self()) is an opaque type, but on some platforms is actually numeric, for example typedefed to unsigned long. On these platforms, is 0 an invalid pthread_t value? What about -1?

Cameron
  • 96,106
  • 25
  • 196
  • 225
  • I'd argue that this isn't a duplicate, because I'm asking about platform-specific behaviour and not the general case. – Cameron Aug 23 '13 at 19:13

1 Answers1

1

If I wanted a value that was either a pthread_t or invalid, I'd use a boost::optional<pthread_t> or std::optional<pthread_t> from C++1y.

This has very little overhead (bytes), expresses what I want (this value may or may not be a pthread_t), and doesn't rely on platform-specific behavior.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Hmm yes, using `optional` or a flag is probably the best general-purpose option. But I'm specifically limiting my usage of `pthread_t` to platforms where it is numeric, precisely because it allows me to use it without any overhead (I'm putting it into a `std::atomic`). – Cameron Aug 23 '13 at 19:12
  • @Cameron `std::optional< std::atomic< pthread_t > >` -- I guess that doesn't let you atomically make the `pthread_t` invalid, or change it from invalid to valid atomically. – Yakk - Adam Nevraumont Aug 23 '13 at 19:12
  • I hadn't thought of inverting it! (Nice trick!) Unfortunately I would need to put the `optional` inside the `atomic` (I'm building a lock-free hash table with thread IDs as keys, and I need to know whether a given slot in the table is free or not based purely on its value, and swap it all at once). I suppose if `sizeof(optional)` was 64-bits I could just use a double-wide CAS operation, though. – Cameron Aug 23 '13 at 19:20