【发布时间】:2010-10-14 05:44:39
【问题描述】:
我遇到了一个奇怪的问题。我有以下代码:
dbg("condwait: timeout = %d, %d\n",
abs_timeout->tv_sec, abs_timeout->tv_nsec);
ret = pthread_cond_timedwait( &q->q_cond, &q->q_mtx, abs_timeout );
if (ret == ETIMEDOUT)
{
dbg("cond timed out\n");
return -ETIMEDOUT;
}
dbg 在每一行之前调用gettimeofday 并在该行前面加上时间。它会产生以下输出:
7.991151: condwait: timeout = 5, 705032704
7.991158: cond timed out
如您所见,两个调试行之间只传递了 7 微秒,但 pthread_cond_timedwait 返回了 ETIMEDOUT。这怎么可能发生?我什至尝试在初始化 cond 变量时将时钟设置为其他值:
int ret;
ret = pthread_condattr_init(&attributes);
if (ret != 0) printf("CONDATTR INIT FAILED: %d\n", ret);
ret = pthread_condattr_setclock(&attributes, CLOCK_REALTIME);
if (ret != 0) printf("SETCLOCK FAILED: %d\n", ret);
ret = pthread_cond_init( &q->q_cond, &attributes );
if (ret != 0) printf("COND INIT FAILED: %d\n", ret);
(不打印任何错误消息)。我尝试了CLOCK_REALTIME 和CLOCK_MONOTONIC。
此代码是阻塞队列的一部分。我需要这样的功能,如果在 5 秒内没有任何东西放在这个队列上,就会发生其他事情。 mutex 和 cond 都已初始化,因为如果我不使用 pthread_cond_timedwait,阻塞队列可以正常工作。
【问题讨论】:
标签: c multithreading conditional system pthreads