Consider this hypothetical situation: a thread takes a mutex lock and allocates some heap memory. Obviously, once the critical section it is in is done, we expect it to free up the heap memory and unlock the mutex. Failure to do this cleanup will cause serious, if not fatal, application bugs (defects) such as memory leakage or deadlock.
But, one wonders, what if the poor thread is canceled prior to the free and unlock? It could happen, right? No! Not if the developer understands and uses the thread cleanup handler mechanism that the pthreads framework provides.
What happens when a thread terminates? The following steps are part of the pthreads cleanup framework:
- All cleanup handlers are popped (reverse order of ...