代码之家  ›  专栏  ›  技术社区  ›  Alex F

usleep是否创建线程取消点?

  •  2
  • Alex F  · 技术社区  · 14 年前

    根据linux手册页,只有以下函数是线程取消点:pthread_join、pthread_cond_wait、pthread_cond_timedwait、pthread_testcancel、sem_wait、sigwait。在我的测试程序中,线程在usleep上退出。线程功能:

    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);
    }
    

    当主函数执行pthread_cancel时,我希望threadFunction打印的最后一行是“检查线程是否已取消…”。但是,它总是在退出前打印“线程迭代…”。这意味着,usleep是取消点。我认为这是正确的-任何睡眠功能都必须取消。但这并不是在文件中写的。

    如果usleep行被注释,最后一个线程输出行是“检查线程是否被取消…”,如我所料。

    2 回复  |  直到 10 年前
        1
  •  9
  •   Anthony Williams    14 年前

    POSIX规范中提供了取消点和可选取消点的完整列表:

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

    usleep() 是强制取消点

        2
  •  0
  •   c9s    10 年前

    我看到了 pthread_testcanel 在mac操作系统的instrument.app中,调用 OSSpinLockLock 功能。

    但乌斯利普似乎没有。