Artyom Chirkov
Artyom Chirkov

Reputation: 363

std::this_thread::sleep_for implementation depends on system clock

The problem I've encountered is that std::this_thread::sleep_for actually uses system clock to calculate the wake time (at least on Windows), not the steady clock. This produces problems when system clock is changed. E.g. if I have a waiting loop with a short wait interval (say 50 ms) and then I set the system clock back for 2 minutes, the loop will stall for 2 minutes instead of 50 ms. That is counterintuitive. I expect it to be 50 ms (+ some small deviation). In any other case this function doesn't make sense if it is possible to wake at random time.

The documentation on sleep_for function says that it is possible to use system clock, but i suppose that is a flaw in the standard. At least there should be a choice of the clock type to use. Or (better) the standard should require the clock to be steady.

So, considering such a flaw, do you know of any other platform-independent way to sleep for definite amount of time?

Upvotes: 8

Views: 2606

Answers (1)

Alex Guteniev
Alex Guteniev

Reputation: 13749

A pull request to address this issue was merged on Oct 21, 2023.

According to change log it landed into VS 2022 17.9, which was first released as a non-Preview version on February 2024, according to the blog post.

Basically, it makes this_thread::sleep_for using Sleep Windows API function directly. So a possible workaround for earlier VS is to use that directly.

There are other places in synchronization facilities still affected by this bug, like condition_variable::sleep_for, a PR to fix these is merged, so hopefully the bug will be completely fixed this year.

Upvotes: 3

Related Questions