Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 thread) but what happens if the thread dies without a gasp?

Should I resign myself to using process signals or can I probe for thread liveliness somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
710 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...