What is Thread Cancellation?
In a multi-threaded program, threads normally run until they call pthread_exit() or return from their start function. But sometimes you need to forcefully stop a thread from outside — this is called thread cancellation.
Real-world examples: a group of worker threads doing a computation — if one detects a fatal error, it should cancel the rest. Or a GUI app with a “Cancel” button that needs to stop a background worker thread. POSIX Threads provides a clean, safe mechanism for this.
All Topics in This Chapter
Learn how to send a cancellation request to another thread using pthread_cancel(). Understand that it only sends the request and does not wait for the thread to stop.
A thread controls whether it accepts cancellation (state) and when it acts on it (type). Covers ENABLE/DISABLE states and DEFERRED/ASYNCHRONOUS types. Also covers fork/exec inheritance rules.
Deferred cancellation only fires at specific “cancellation points” — special functions listed by SUSv3. Includes the full table of required functions, optional functions, SUSv4 changes, and how PTHREAD_CANCELED is returned via pthread_join().
Compute-bound threads may never reach a natural cancellation point. pthread_testcancel() manually introduces a cancellation point inside any loop or hot path.
When a thread is canceled mid-way, mutexes may remain locked and memory may leak. Cleanup handlers are functions automatically called on cancellation to restore consistent state. Covers the handler stack, push/pop macros, and the lexical-block pairing rule.
Asynchronous cancellation allows a thread to be stopped at any machine instruction. Explains why this is dangerous, which functions are async-cancel-safe, and the only scenario where it is genuinely safe to use.
Full chapter summary, quick-reference API table, key rules to remember, and a complete set of interview questions covering all topics.
