I'm a little confused about clean-up order when you're using PThreads with regard to cancellation. Normally, if your thread is detached, it automatically cleans up when it terminates. If it's not detached, you need to join it to reclaim the system resources.
The textbook I'm reading states the following which strangely sounds like joining is optional with regard to cancellation:
"If you need to know when the thread has actually terminated, you must join with it by calling pthread_join after cancelling it."
So, do I need to join a cancelled thread to free its resources - and if not, then why?
Thread cancellation lets a thread terminate the execution of any other thread in the process. When a cancellation requested is acted on, the target thread (the thread being cancelled) is allowed to defer cancellation requests and to perform application-specific cleanup processing.
no, you can detach one thread if you want it to leave it alone. If you start a thread, either you detach it or you join it before the program ends, otherwise this is undefined behaviour.
Yes if thread is attachable then pthread_join is must otherwise it creates a Zombie thread. Agree with answers above, just sharing a note from man page of pthread_join. After a successful call to pthread_join(), the caller is guaranteed that the target thread has terminated.
DESCRIPTION top. The pthread_cancel() function sends a cancellation request to the thread thread. Whether and when the target thread reacts to the cancellation request depends on two attributes that are under the control of that thread: its cancelability state and type.
TLPI says this:
Upon receiving a cancellation request, a thread whose cancelability is enabled and deferred terminates when it next reaches a cancellation point. If the thread was not detached, then some other thread in the process must join with it, in order to prevent it from becoming a zombie thread.
Also, since canceling a thread isn't usually done immediately (read more about "cancellation points") without joining you can't be sure the thread was actually canceled.
From man pthread_join
:
After a canceled thread has terminated, a join with that thread using pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status. (Joining with a thread is the only way to know that cancellation has completed.)
It seems that joining is not necessary for execution it is necessary if you want know what you did actually succeed.
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