Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to join a cancelled thread? (pthreads)

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?

like image 216
John Humphreys Avatar asked Jan 23 '12 16:01

John Humphreys


People also ask

What happens when a thread is Cancelled?

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.

Do I have to join threads?

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.

Is Pthread join necessary?

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.

What does Pthread cancel do?

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.


2 Answers

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.

like image 175
cnicutar Avatar answered Sep 28 '22 07:09

cnicutar


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.

like image 33
pmr Avatar answered Sep 28 '22 08:09

pmr