Cleaning up at thread exit

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:

  1. All cleanup handlers are popped (reverse order of ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.