views:

55

answers:

1

According to the Linux manpages, only the following functions are thread cancellation points: pthread_join, pthread_cond_wait, pthread_cond_timedwait, pthread_testcancel, sem_wait, sigwait. In my test program, thread exits on usleep. Thread function:

void* ThreadFunction(void* arg)
{
    int n = 0;

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);

    for(;;)
    {
        ostringstream s;
        s << "Thread iteration " << n++;
        PrintLine(s.str().c_str());

        usleep(500000);

        PrintLine("Check whether thread canceled...");
        pthread_testcancel();
        PrintLine("Thread is not canceled - continue");
    }

    pthread_exit(NULL);
}

When main function executes pthread_cancel, I expect that last line printed by ThreadFunction is "Check whether thread canceled...". However, it always prints "Thread iteration ..." before exit. This means, usleep is cancellation point. I think that it is correct - any sleep function must be cancellable. But this is not written in documentation.

If usleep line is commented, last thread output line is "Check whether thread canceled...", as I expect.

+7  A: 

The complete list of cancellation points and optional cancellation points is available in the POSIX spec:

http://opengroup.org/onlinepubs/007908775/xsh/threads.html

usleep() is a mandatory cancellation point

Anthony Williams
`boost::thread` knows :)
Nikolai N Fetissov
+1: Almost exactly what I was going to say. Here's an alternative URL (later [POSIX](http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_09) standard) for the same information.
Jonathan Leffler