pthreads,mq_timedreceive,pthread_cond_timedwait 和 CLOCK_REALTIME

pthreads, mq_timedreceive, pthread_cond_timedwait and CLOCK_REALTIME

我正在使用一个实现了两个 posix 函数的系统

mq_timedreceive() and pthread_cond_timedwait()

这两个函数都使用基于 CLOCK_REALTIME 的绝对超时。此时钟在系统启动期间的不同时间发生变化,可以向后或向前移动 10 秒到几小时。

公开组说:

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock; if the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function. (mq_timedreceive)

For cases when the system clock is advanced discontinuously by an operator, it is expected that implementations process any timed wait expiring at an intervening time as if that time had actually occurred. (pthread_cond_timedwait()).

然而,这在时钟向后设置的情况下没有提供任何指导。

QNX 通过提供

解决了这个问题
mq_timedreceive_monotonic().

The mq_timedreceive_monotonic() function is a QNX Neutrino extension; it's similar to mq_timedreceive(), but it uses CLOCK_MONOTONIC, so the timeout isn't affected by changes to the system time.

在linux中有实现QNX功能的好方法吗?

对于 mq_timedreceive() 我可以使用 mq_receive() 和 poll()。但是对于条件变量我还没有想出一个干净的方法。我可以使用定时器和信号,但这似乎太复杂了。

当然,另一种解决方案是不调整时钟或使用从 CLOCK_MONOTONIC 派生的不同时钟,但我无权更改设计。

您可以更改条件变量 pthread_cond_timedwait() 使用的时钟,方法是在条件变量初始化时更改其时钟属性,使用 pthread_condattr_setclock()