What exactly is a cancellation point?

code_fodder picture code_fodder · Dec 9, 2014 · Viewed 11.9k times · Source

I am trying to get my head around what exactly a cancellation point is in c++. I have read:

man page and What are pthread cancellation points used for

But I am still a little confused on certain points. For example, I am using the file write() function. Apparently this is a cancellation point. So when I call write(), I can see that another thread may start processing (so my code switches from the writing thread to another thread), this usually happens when the write-to buffer is full and needs to be emptied before the write() can succeed/complete.

But in my mind, this is not a cancellation of a thread, but merely a temporary blocking/suspend, and there is no thread "cleanup" to do...

So my question is, do cancellation points have relation to "blocking points"? - are they really the same thing, or is there some difference? Any clear "top-level" description of what a cancellation point is would be really useful.

Answer

Bogdan V. picture Bogdan V. · Dec 9, 2014

When your thread gets pulled from execution, its state is saved by the OS and that is not a cancellation of the thread. The cancellation means thread termination, on request, with the specific intent of letting everything in a final state when completed (aka. all resources are freed, all handlers are updated, etc.).

What you call blocking can happen to a thread while in mid-cancellation.

Example: The thread gets a cancellation request. The OS queues it until the thread becomes cancellable. When the thread becomes cancellable, and the thread is executing a cancel point, the thread can be cleaned and cancelled. The write function is a cancellation point, this meaning it is safe from the point of view of the OS to cancel the thread while this function is executed (the state of all related resources will be consistent).

While the cancellation procedure is running, the thread can be blocked as many times as the OS seems fit.

As an additional note, if you look at the POSIX requirement for cancel points, virtually all blocking interfaces are required to be cancel points. Otherwise, on any completely blocked thread (in such call), there would be no safe way to terminate that thread.

http://man7.org/linux/man-pages/man7/pthreads.7.html