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 i
From Doccumentation of pthread_cancel()
:
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.)
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.
If something goes wrong in a thread or it is stopped from with in somehow it will always be tidied up by the OS. So it's all nice and safe.
You only need to join the thread if you have to be sure it has actually stopped executing, like merging two parallel tasks. (E.g. if you have various threads working on various parts a split structure you need to join them all, as in wait until they are all finished, when you want to combine the structure again)
A thread using pthread can have following cancelling statuses:
PTHREAD_CANCEL_ENABLE PTHREAD_CANCEL_DISABLE
If you try to cancel a thread you do not 100% know if the thread will really get cancelled. Using a join delivers the information to you if the thread was really cancelled or not. There are also cancel types to be considered and respective pthread functions for setting the cancel type and state:
int pthread_setcancelstate (int state, int *oldstate); int pthread_setcanceltype (int type, int *oldtype);
Here is a sample code borrowed from http://www.ijon.de/comp/tutorials/threads/cancel.html
EDIT: Either I am too stupid to post a few lines of code or the formatter is really going on my nerves today. Just look up the code in the link above, please.
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.