问题描述
我有一个奇怪的问题。我有以下的code:
I'm having a strange problem. I have the following code:
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的
每一行和prepends前的时间线。它导致的输出如下:
dbg
calls gettimeofday
before every line and prepends the line with the time. It results in the following output:
7.991151: condwait: timeout = 5, 705032704
7.991158: cond timed out
正如你所看到的,只有7微秒两调试线之间传递,但那么pthread_cond_timedwait
返回 ETIMEDOUT
。这怎么可能发生?我甚至尝试初始化COND变量时,时钟设置别的东西:
As you can see, only 7 microseconds passed in between the two debug lines, yet pthread_cond_timedwait
returned ETIMEDOUT
. How can this happen? I even tried setting the clock to something else when initializing the cond variable:
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
。
这code是一个阻塞队列的一部分。我需要的功能,例如,如果没有获取在5秒钟内把这个队列,别的事情发生。互斥和COND都被初始化,因为阻塞队列,如果我不使用正常工作那么pthread_cond_timedwait
。
This code is part of a blocking queue. I need functionality such that if nothing gets put on this queue in 5 seconds, something else happens. The mutex and the cond are both initialized, as the blocking queue works fine if I don't use pthread_cond_timedwait
.
推荐答案
那么pthread_cond_timedwait需要一个绝对时间,而不是一个相对时间。你需要让你的等待时间绝对加入到当前的时间,你的超时值。
pthread_cond_timedwait takes an absolute time, not a relative time. You need to make your wait time absolute by adding to the current time to your timeout value.
这篇关于那么pthread_cond_timedwait立即返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!