How do I determine if a detached pthread is alive?

For a joinable (i.e NOT detached) pthread you could use pthread_kill like this:

int ret = pthread_kill(YOUR_PTHREAD_ID, 0);

If you get a ESRCH value, it might be the case that your thread is dead.

However this doesn’t apply to a detached pthreads because after it has ended its thread ID can be reused for another thread.

From the comments:

The answer is wrong because if the thread is detached and is not
alive, the pthread_t is invalid. You can’t pass it to pthread_kill. It
could, for example, be a pointer to a structure that was freed,
causing your program to crash. POSIX says, “A conforming
implementation is free to reuse a thread ID after its lifetime has
ended. If an application attempts to use a thread ID whose lifetime
has ended, the behavior is undefined.” – Thanks @DavidSchwartz

Leave a Comment