Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

windows

c++11

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?

like image 648
Artyom Chirkov Avatar asked Jul 01 '26 19:07

Artyom Chirkov


1 Answers

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.

like image 129
Alex Guteniev Avatar answered Jul 04 '26 12:07

Alex Guteniev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!