等待std :: condition_variable时如何处理系统时钟更改? [英] How do I deal with the system clock changing while waiting on a std::condition_variable?

查看:524
本文介绍了等待std :: condition_variable时如何处理系统时钟更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C ++ 11中实现一些跨平台代码。此代码的一部分使用 std :: condition_variable 实现了信号量对象。当我需要对信号量进行定时等待时,可以使用 wait_until 或wait_for。

I'm trying to implement some cross-platform code in C++11. Part of this code implements a semaphore object using a std::condition_variable. When I need to do a timed wait on the semaphore, I use wait_until or wait_for.

我遇到的问题是,基于POSIX的系统上condition_variable的标准实现似乎依赖于使用系统时钟,而不是单调时钟(另请参见:针对POSIX规范的问题

The problem I'm experiencing is that it seems like the standard implementation of condition_variable on POSIX-based systems relies on the system clock, rather than the monotonic clock (see also: this issue against the POSIX spec)

如果系统时钟更改为过去的某个时间,我的条件变量的阻塞时间将比我预期的要长得多。例如,如果我希望我的condition_variable在1秒后超时,如果有人在等待期间将时钟调整回10分钟,则condition_variable会阻塞10分钟+ 1秒。我已经确认这是在Ubuntu 14.04 LTS系统上的行为。

That means that if the system clock gets changed to some time in the past, my condition variable will block for far longer than I expect it to. For instance, if I want my condition_variable to time out after 1 second, if someone adjusts the clock back 10 minutes during the wait, the condition_variable blocks for 10 minutes + 1 second. I've confirmed that this is the behavior on an Ubuntu 14.04 LTS system.

我需要依靠此超时来至少在一定程度上是准确的(即,在一定的误差范围内可能不准确,但是如果系统时钟仍然需要执行,变化)。看来我需要做的是编写自己的condition_variable版本,该版本使用POSIX函数并使用单调时钟实现相同的接口。

I need to rely on this timeout to be at least somewhat accurate (ie, It can be inaccurate within some margin of error, but still needs to execute if the system clock changes). It seems like what I'm going to need to do is write my own version of condition_variable that uses the POSIX functions and implements the same interface using the monotonic clock.

这听起来像是很多工作-有点混乱。还有其他方法可以解决此问题吗?

That sounds like A Lot Of Work - and kind of a mess. Is there some other way of working around this issue?

推荐答案

在考虑了可能解决此问题的方法之后,似乎可以最有意义的是禁止使用std :: condition_variable(或至少要说明,它总是要使用系统时钟)。然后,我必须以尊重时钟选择的方式从根本上重新实现标准库的condition_variable。

After considering the possible solutions to this problem, the one that seems to make the most sense is to ban the use of std::condition_variable (or at least make the caveat clear that it is always going to use the system clock). Then I have to basically re-implement the standard library's condition_variable myself, in a way that respects the clock choice.

由于我必须支持多个平台(Bionic,POSIX,Windows以及最终的MacOS),所以我将维护该代码的多个版本。

Since I have to support multiple platforms (Bionic, POSIX, Windows, and eventually MacOS), that means I'm going to maintain several versions of this code.

虽然这很讨厌,但似乎替代品甚至更讨厌。

While this is nasty, it seems like the alternatives are even nastier.

这篇关于等待std :: condition_variable时如何处理系统时钟更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆