pthreads、mq_timedreceive、pthread_cond_timedwait 和 CLOCK_REALTIME

标签 pthreads message-queue condition-variable

我正在使用一个实现了两个 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() .

关于pthreads、mq_timedreceive、pthread_cond_timedwait 和 CLOCK_REALTIME,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873374/

相关文章:

c - 消息队列不接受 0 作为参数

c++ - 用于线程间通信的 volatile 和 mutex

C++ 生产者消费者陷入死锁

无法创建 posix 消息队列

c++ - 与 std::condition_variable_any 相关的开销是多少

c - 我试图在 thread_func 调用中通过 for 循环的每次传递请求打印线程数

c - 抢占、pthread_spin_lock 和原子内置

c - 适本地存储线程特定变量

c++ - Pthreads 和动态内存

java - Rabbitmq:消费前修改消息正文