Canceling a thread – a code example

A simple code example demonstrating thread-cancelation follows; we have the main thread create two worker threads (think of them as thread A and thread B) and then have the main thread cancel thread A. In parallel, we deliberately have thread A disable cancelation (by setting the cancelation state to disabled), do some bogus work (we call our trusty DELAY_LOOP macro to simulate work), then re-enable cancelation. The cancelation request takes effect at the next cancelation point (as, of course, the type defaults to deferred), which, here, is simply the sleep(3) API.

The code demonstrating thread cancelation (ch16/cancelit.c) follows.

For readability, only key parts of the source code are displayed here. ...

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.