Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a detached pthread is alive?

Tags:

linux

pthreads

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?

like image 543
jldupont Avatar asked Nov 07 '09 14:11

jldupont


People also ask

How do you check if a pthread is still running?

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.

What is a detached pthread?

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.

How do I find my current pthread?

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.

Are detached threads joinable?

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).


1 Answers

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

like image 51
Pablo Santa Cruz Avatar answered Sep 24 '22 17:09

Pablo Santa Cruz