根据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);
}
当main函数执行pthread_cancel时,我希望ThreadFunction打印的最后一行是“检查线程是否被取消......” . 但是,它总是在退出之前打印“Thread iteration ...” . 这意味着,usleep是取消点 . 我认为这是正确的 - 任何睡眠功能都必须是可取消的 . 但这不是在文档中写的 .
如果usleep行被注释,最后一个线程输出行是“检查线程是否被取消...”,正如我所期望的那样 .
2 回答
POSIX规范中提供了取消点和可选取消点的完整列表:
http://opengroup.org/onlinepubs/007908775/xsh/threads.html
usleep()
是强制取消点我在Mac OS上的Instrument.app中看到了
pthread_testcanel
的调用树,它调用OSSpinLockLock
函数 .但是睡着似乎没有 .