开发者

How do I determine if a detached pthread is alive?

开发者 https://www.devze.com 2022-12-11 06:47 出处:网络
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

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?


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


This question assumes a design with an unavoidable race condition.

Presumably, you plan to do something like this:

  1. Check to see if thread is alive
  2. Wait for message from thread

The problem is that this sequence is not atomic and cannot be fixed. Specifically, what if the thread you are checking dies between step (1) and step (2)?

Race conditions are evil; rare race conditions doubly so. Papering over something 90% reliable with something 99.999% reliable is one of the worst decisions you can make.

The right answer to your question is "don't do that". Instead, fix your application so that threads do not die randomly.

If that is impossible, and some thread is prone to crashing, and you need to recover from that... Then your design is fundamentally flawed and you should not be using a thread. Put that unreliable thing in a different process and use a pipe to communicate with it instead. Process death closes file descriptors, and reading a pipe whose other end has been closed has well-defined, easily detected, race-free behavior.


It is probably undefined behaviour when you send a signal to an already dead thread. Your application might crash. see http://sourceware.org/bugzilla/show_bug.cgi?id=4509 and http://udrepper.livejournal.com/16844.html

0

精彩评论

暂无评论...
验证码 换一张
取 消