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?
How can I tell if my thread is still running? Answer: You can add a "thread_complete" flag to do the trick: Scenario: Thread A wants to know if Thread B is still alive. When Thread B is created, it is given a pointer to the "thread_complete" flag address.
The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are automatically released back to the system without the need for another thread to join with the terminated thread.
pthread_self() in C The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.
a joinable thread? Performance-wise, there's no difference between joinable threads vs detached threads. The only difference is that with detached threads, its resources (such as thread stack and any associated heap memory, and so on - exactly what constitutes those "resources" are implementation-specific).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With