开发者

Does usleep create thread cancellation point?

开发者 https://www.devze.com 2023-01-07 02:28 出处:网络
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, 开发者_StackOverflo

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, 开发者_StackOverflow社区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.


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


I saw the call tree of pthread_testcanel in Instrument.app on Mac OS, which calls OSSpinLockLock function.

but usleep seems not.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号