How do I determine if a detached pthread is alive?

后端 未结 3 1145
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 07:39

How do I determine if a detached pthread is still alive ?

I have a communication channel with the thread (a uni-directional queue pointing outwards from the

3条回答
  •  独厮守ぢ
    2020-12-01 08:35

    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

提交回复
热议问题