【发布时间】:2014-05-29 09:28:53
【问题描述】:
我编写了很好的监听 UDP 消息的功能,每当有新消息到达时,这些消息就会被添加到 FIFO 中,并且会向监听器发出信号。
如果没有其他事情可做,侦听器会等待消息。但是,它知道,在某些情况下,它应该在很短的时间内醒来。所以我编写了使用 pthread_cond_timedwait() 的代码,然后我将当前测试中的时间设置为大约 1.5 秒。
它确实等待 1 秒,然后等待功能不再阻塞。这是否意味着当前的实现不支持亚秒级(毫秒/微秒等待)?
有一点我的输出。我从 1417 毫秒开始,第一次尝试似乎要等待 1001 毫秒。然后在每次后续尝试中花费 0 或 1 毫秒,完全没有阻塞。
image transform ending with [1416272]
wait for 1417 till 1401354361 now = 1401354360
image transform ending with [415259]
wait for 416 till 1401354361 now = 1401354361
image transform ending with [414759]
wait for 415 till 1401354361 now = 1401354361
image transform ending with [414196]
wait for 415 till 1401354361 now = 1401354361
image transform ending with [413646]
wait for 414 till 1401354361 now = 1401354361
image transform ending with [413013]
wait for 414 till 1401354361 now = 1401354361
image transform ending with [412385]
wait for 413 till 1401354361 now = 1401354361
image transform ending with [411801]
wait for 412 till 1401354361 now = 1401354361
image transform ending with [411237]
wait for 412 till 1401354361 now = 1401354361
image transform ending with [410690]
wait for 411 till 1401354361 now = 1401354361
image transform ending with [410204]
wait for 411 till 1401354361 now = 1401354361
image transform ending with [409728]
wait for 410 till 1401354361 now = 1401354361
image transform ending with [409150]
wait for 410 till 1401354361 now = 1401354361
image transform ending with [408566]
wait for 409 till 1401354361 now = 1401354361
image transform ending with [408004]
...snip...
wait for 3 till 1401354361 now = 1401354361
image transform ending with [2188]
wait for 3 till 1401354361 now = 1401354361
image transform ending with [1628]
wait for 2 till 1401354361 now = 1401354361
image transform ending with [1077]
wait for 2 till 1401354361 now = 1401354361
image transform ending with [221]
wait for 1 till 1401354361 now = 1401354361
等待函数:
void wait(int msecs)
{
if(msecs == -1)
{
pthread_cond_wait(&f_condition, &f_mutex.f_mutex);
}
else if(msecs > 0)
{
struct timeval tod;
gettimeofday(&tod, nullptr);
struct timespec ts;
ts.tv_sec = tod.tv_sec + msecs / 1000;
ts.tv_nsec = tod.tv_usec * 1000 + msecs % 1000;
ts.tv_sec += ts.tv_nsec / 1000000000L;
ts.tv_nsec = ts.tv_nsec % 1000000000L;
std::cerr << "wait for " << msecs << " till " << ts.tv_sec << " now = " << time(NULL) << "\n";
pthread_cond_timedwait(&f_condition, &f_mutex.f_mutex, &ts);
}
}
【问题讨论】:
-
你想发布一些代码吗? :-)
-
当这种情况发生时,您从
pthread_cond_timedwait()看到什么返回码? -
好的,我添加了wait()函数本身的代码。它是在互斥锁锁定的情况下调用的。调用返回的代码是 110,代表
#define ETIMEDOUT 110 /* Connection timed out */。所以它认为current time >= ts... -
不应该是
ts.tv_nsec = tod.tv_usec * 1000 + msecs * 1000 * 1000吗?您似乎是将毫秒除以 1000(即计算秒单位)然后将其添加到纳秒单位中。 -
@6EQUJ5:我想你已经找到问题了,但我认为实际的表达应该是:
ts.tv_nsec = tod.tv_usec * 1000 + (msecs % 1000) * 1000 * 1000
标签: linux pthreads wait milliseconds