Is relation between this_thread::sleep_for and chrono clocks specified by C++11 standard?

Viewed 210

Consider following code:

using namespace std;
using namespace std::chrono;
typedef std::intmax_t intmax_type;

steady_clock::time_point start = steady_clock::now();

this_thread::sleep_for(chrono::milliseconds(25000));

steady_clock::duration dur = steady_clock::now() - start;

intmax_type desired_dur = duration_cast<milliseconds>(dur).count();

if(desired_dur < intmax_type(25000))
    std::cout << "WTF happend there?" << std::endl;

According to standard std::this_thread::sleep_for(sleep_duration) may block for longer than sleep_duration due to scheduling or resource contention delays but at least it blocks thread execution for the specified sleep_duration.

There may be situation when the thread actually sleeps for specified duration but due to std::chrono::steady_clock or std::chrono::system_clock using different OS clocks than sleep_for implementation (different granularity f.e.) time period measurement gives us different result than actual sleep time was.

My question is:

Is it prohibited by C++11 standard for condition if(desired_dur < intmax_type(25000)) to happen? If so provide the exact quotes please.

1 Answers

It is prohibited by C++11/14/17/20 for desired_dur < intmax_type(25000) to be true.

Here is the spec for this_thread::sleep_for:

Effects: Blocks the calling thread for the relative timeout (32.2.4) specified by rel_time.

The reference to 32.2.4 is here. This is a very long-winded section which defines rel_time as a relative timeout. Probably the most important paragraph is p3:

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.326 Given a duration argument Dt, the real-time duration of the timeout is Dt + Di + Dm.

326) All implementations for which standard time units are meaningful must necessarily have a steady clock within their hardware implementation.

The section defines Di as a “quality of implementation” delay, and Dm as a “quality of management” delay. These definitions imply (by the use of "delay") that they are non-negative quantities of time duration.

The term "steady clock" is never actually defined but the standard does say this about steady_clock:

Objects of class steady_clock represent clocks for which values of time_point never decrease as physical time advances and for which values of time_point advance at a steady rate relative to real time. That is, the clock may not be adjusted.

The use of the word "should" in the sentence:

Implementations should use a steady clock

is wiggle room. "should" means:

We really want you to, but you don't have to. You can still call yourself conforming if you don't.

"should" is used instead of "shall" here because there is no such thing as a perfect clock, especially inside your consumer grade computer.

Related