Subj : Re: pthread_cancel To : comp.programming.threads From : David Butenhof Date : Wed May 11 2005 11:41 am Ed Skinner wrote: > On Mon, 09 May 2005 03:39:52 +0000, Greg Law wrote: > >>void >>Start (void *a) { >> int tmp; >> int r = pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, &tmp); assert >> (!r); >> r = pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &tmp); assert >> (!r); >> >> while (1) { >> printf ("%d\n", tmp++); >> } >> } >> } > I think main() is firing off the pthread_cancel() BEFORE the thread > has an opportunity to run and set the deferred cancel state. This is quite likely. and a very good point to keep in mind. However in this case it's also irrelevant. ;-) The cancellation state that the thread goes to so much trouble to set up ("enabled" and "deferred") is in fact defined by POSIX/UNIX to be the default initial state of EVERY thread. If either of these setup calls ever changes anything of significance to the program, then the implementation is broken. (Or perhaps less prejudicially, "it is not POSIX".) Furthermore, there's only one possible cancellation point in the thread, printf(). (That is, aside from the assert() calls when built debug, and in the entirely unlikely case that one of the redundant cancelability state operations should fail.) As others have said already, the real answer is that printf() is one of those functions on the second list of cancellation points. It is ALLOWED but not REQUIRED to invoke cancellation if a cancel is pending or arrives during execution. On some implementations, printf() always runs with cancellation disabled so that when printf() calls write() the library doesn't need to deal with cleanup. On other implementations printf() will act as a cancellation point when the file stream is unbuffered, or when printf() decides to flush its buffer via write(). And on yet others, printf() might test for a pending cancel even when it doesn't call write(). All of these are legal implementations; and an application that cannot run correctly under all these variations is non-conforming. (And note that while writing non-conforming implementations is almost always bad, writing non-conforming APPLICATIONS can be fine as long as you know what you're doing. But please do make sure that, like Picasso, you UNDERSTAND all the rules before you decide which ones you wish to break. ;-) ) -- Dave Butenhof, David.Butenhof@hp.com HP Utility Pricing software, POSIX thread consultant Manageability Solutions Lab (MSL), Hewlett-Packard Company 110 Spit Brook Road, ZK2/3-Q18, Nashua, NH 03062 .