What is the default clock type of std::chrono::duration?

137 views Asked by At

I've seen that there are 2 different clock types, steady_clock (monotonic clock) and system_clock (wall clock). If I use std::chrono::duration to wait some time, e.g.:

cv.wait_for( lock, std::chrono::milliseconds(10000));

So what's the default clock type of std::chrono::milliseconds(10000)? If I want to sleep for 10s, and the computer os has slept very long time after wait for 2s, after the OS awake, would it continue sleep for another 8s or end sleep?

1

There are 1 answers

0
Howard Hinnant On

Clocks are not associated with duration in any way. However, if you go to the definition of condition_variable::wait_for you can see that the answer to your question in this case is steady_clock.

And in general, you'll have to look somewhere besides duration to find out if a "default clock" is in effect.

For sleep_for, it looks more promising than it is. The requirements are not spelled out at the definition of sleep_for, but you are referred to [thread.req.timing].

Here it says:

The functions whose names end in _for take an argument that specifies a duration. These functions produce relative timeouts. Implementations should use a steady clock to measure time for these functions.

  • "a steady clock" does not mean steady_clock. It means a clock for which the nested value is_steady is true.

  • "should" doesn't mean "shall". "Should" means that implementations are encouraged to do it, but not required to do it. "Shall" means implementations do it, or are not conforming to the standard.

So sleep_for doesn't have a "default clock".

On how long a thread might "sleep" or "wait": The short answer is that it will sleep or wait for at least as long as the argument says it will. And it may sleep/wait longer. How much longer? As long as it wants to.

The longer answer is in [thread.req.timing].