我对 pthread_cond_timedwait() 有一个奇怪的问题:根据 POSIX 规范,它是一个取消点。但是,当我在线程上调用 pthread_cancel() 时,它永远不会被取消!相反, pthread_cond_timedwait() 继续正常运行。它没有锁定或任何东西,它只是继续运行,就好像从未调用过 pthread_cancel() 一样。但是,只要我插入 pthread_testcancel() 调用,线程就会被正确取消!如果没有调用 pthread_testcancel(),线程永远不会被取消,尽管我一直在调用 pthread_cond_timedwait()。
有人知道这里出了什么问题吗?非常感谢!
编辑:这里是代码:
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
// replacement function because OS X doesn't seem to have clock_gettime()
static int clock_gettime(int clk_id, struct timespec* t)
{
struct timeval now;
int rv = gettimeofday(&now, NULL);
if(rv) return rv;
t->tv_sec = now.tv_sec;
t->tv_nsec = now.tv_usec * 1000;
return 0;
}
static void *threadproc(void *data)
{
pthread_mutex_t mutex;
pthread_mutexattr_t attr;
pthread_cond_t cond;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
pthread_cond_init(&cond, NULL);
for(;;) {
struct timespec ts;
clock_gettime(0, &ts);
// wait 60ms
ts.tv_nsec += 60 * 1000000;
pthread_mutex_lock(&mutex);
pthread_cond_timedwait(&cond, &mutex, &ts);
pthread_mutex_unlock(&mutex);
#if 0
pthread_testcancel();
#endif
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t pThread;
pthread_create(&pThread, NULL, threadproc, NULL);
printf("Waiting...\n");
sleep(5);
printf("Killing thread...\n");
pthread_cancel(pThread);
pthread_join(pThread, NULL);
printf("Ok!\n");
return 0;
}