Is there an invalid pthread_t id? Is there an invalid pthread_t id? linux linux

Is there an invalid pthread_t id?


Your assumption is incorrect to start with. pthread_t objects are opaque. You cannot compare pthread_t types directly in C. You should use pthread_equal instead.

Another consideration is that if pthread_create fails, the contents of your pthread_t will be undefined. It may not be set to your invalid value any more.

My preference is to keep the return values of the pthread_create calls (along with the thread IDs) and use that to determine whether each thread was started correctly.


As suggested by Tony, you can use pthread_self() in this situation.

But do not compare thread_ts using == or !=. Use pthread_equal.

From the pthread_self man page:

Therefore, variables of type pthread_t can't portably be compared using the C equality operator (==); use pthread_equal(3) instead.


I recently ran into this same issue. If pthread_create() failed, I ended up with a undefined, invalid value stored in my phtread_t structure. As a result, I keep a boolean associated with each thread that gets set to true if pthread_create() succeeded.

Then all I need to do is:

void* status;if (my_thread_running) {  pthread_join(thread, &status);  my_thread_running = false;}