Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

linux - How do I determine if a detached pthread is alive?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...