我有一个奇怪的问题。我有以下代码:
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
calls 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
and CLOCK_MONOTONIC
.
此代码是阻塞队列的一部分。我需要这样的功能:如果 5 秒内没有任何内容放入此队列,则会发生其他情况。互斥锁和条件都已初始化,因为如果我不使用阻塞队列,则可以正常工作pthread_cond_timedwait
.