Subj : Re: pthread_cancel To : comp.programming.threads From : Ed Skinner Date : Tue May 10 2005 11:09 am On Mon, 09 May 2005 03:39:52 +0000, Greg Law wrote: > Hi, > > I am calling pthread_cancel on a thread that has canceling enabled, of > deferred type. The thread I am canceling never makes any calls to > testcancel, or waits on any condition variables. So it surprises me > that the cancelation has any effect at all. That is, in the following > program the thread I've created is terminated (to my surprise). I guess > I've not understood correctly when threads may be canceled? > > Cheers, > > Greg > > > #include > #include > > 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++); > } > } > } > int > main (void) { > int r = 0; > pthread_t p; > > r = pthread_create (&p, NULL, (void*)Start, 0); printf ("%d: %ld\n", > r, p); > > r = pthread_cancel (p); > printf ("back from cancel (%d)\n", r); while (1); > } > } > } I think main() is firing off the pthread_cancel() BEFORE the thread has an opportunity to run and set the deferred cancel state. (In a simple situation such as this it is highly likely that main() will continue to be the thing that executes -- doing a pthread_create() merely creates the new thread but does not guarantee that the new thread will actually execute -- main() needs to do something to give the new thread an opportunity to execute and a sleep(1) will do precisely that.) Try adding a sleep(1) in main() between the pthread_create() and the pthread_cancel() to give the thread an opportunity to run and protect itself. .