Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c++ - How do I deal with the system clock changing while waiting on a std::condition_variable?

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.

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)

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Register your active condition variables centrally.

Do some effort to detect the clock error, even if it is a thread spin-locking on the current clock (ick) or some other means.

When you detect a clock error, poke the condition variable.

Now wrap your condition variables in a thin wrapper that also supports detecting the clock slippage. It invokes wait_until but replaces the predicate with one that detects clock slippage, and when that happens breaks out of the wait.

When your implementation is broken, you gotta do what you gotta do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...