Sources Bugzilla – Bug 13613
Cancellation is broken in single-threaded processes
Last modified: 2012-05-15 04:14:51 UTC
Cancellation is not acted upon unless the process has more than one thread.
Consider the program:
read(0, &c, 1);
Being a cancellation point, read should cause the pending cancellation request
to be acted upon, and the program should terminate with status 0 as a
consequence of the last thread exiting from cancellation. However, under
glibc/NPTL, the program waits for input then terminates with status 1.
I suspect the cancellation wrapper code is incorrectly checking SINGLE_THREAD_P
and (wrongly) assuming that it implies cancellation is impossible.
Ping. Anyone looked at this?
Async cancellation points get activated only when the number of threads are
greater than 1, which is why you're seeing the behaviour you see. What is your
use case anyway? I don't see why something like this should be needed at all.
Of course, I couldn't find anything in the posix definition of pthread_cancel
to not allow something like this:
I don't have a specific usage case in mind, and I don't suspect anyone would
intentionally try to cancel the main thread in a single-threaded program
knowing it's the main thread. Where the issue is likely to matter is in code
that doesn't know it's dealing with the main thread of a single-threaded
program, e.g. in a library.
The type of application it's likely to affect is an application that does `N`
jobs in parallel by spawning `N-1` threads and using the main thread as a
worker thread. As an example, I have a parallel DNS resolver tool that does
this. If it turns out that `N` is 1, no threads get created, and the process
runs single-threaded. My DNS resolver does not have the threads using
pthread_cancel on themselves, but I could imagine moderately-contrived cases
where you might want to do this. Self-cancellation is a nice way to setup
future code to abort if it does anything that would block, while avoiding
exiting immediately. (And if you've written your program this way, you can
still call functions that are cancellation points if you temporarily block
cancellation around the call.)
In any case, glibc's behavior is non-conformant. POSIX does not make any
exceptions to the rules about how cancellation works for the special case of
single-threaded programs. (In fact the only special case I can find that POSIX
makes for single-threaded programs is that you're allowed to call
async-signal-unsafe functions after fork() in a single-threaded program.)
If anything, pthread_cancel should for self-cancellation (with a comment)
THREAD_SETMEM (THREAD_SELF, header.multiple_threads, 1);
__pthread_multiple_threads = *__libc_multiple_threads_ptr = 1;
Then this will work just fine, without any overhead in the common path, except
a few insns in the already slow pthread_cancel.
I agree that's a simple and acceptable fix.
I have submitted a patch for review:
Fix committed to master. Thanks for reporting this.