Thread Cancellation Example

  • Create a thread

  • Try to cancel it

  • Wait for it to finish

pthread_create(&thread, NULL, thread_func, NULL);
pthread_cancel(thread);
pthread_join(thread, NULL);
  • Mark the thread as non-cancellable

    • ... while it works

    • ... and until we allow cancellation

    • ... and reach a cancellation point

pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
...
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_testcancel();
  • Make the thread cancellable at any time

  • But for now mark it in a non-cancellable state

    • ... while it works

    • ... and until we allow cancellation

  • The thread is cancelled automatically, no need to reach a cancellation point

threads-cancel.c

Compiling the program with explicit instruction to the compiler to support threads:

Last updated

Was this helpful?