Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is behaviour well-defined when `sleep_until()` specifies a time point in the past?

The C++11 standard talks about what should happen if the system clock is adjusted such that the time point passed to sleep_until() is now in the past - but I can't see anywhere that addresses the case when the specified time point is already in the past.

Have I simply overlooked something, or is it really not specified - even as UB or implementation-defined?

A similar question arises if sleep_for() is invoked with a negative duration.

like image 908
Jeremy Avatar asked Oct 04 '16 09:10

Jeremy


2 Answers

Calculation of time until which to sleep and calling sleep_until() is not atomic. It is possible that you calculate time, then context switch occurs, system is overloaded, swapping, and actual call to sleep_until() happens much later. So if sleep_until() does not wake up when time is in the past, then it is useless, because in such situation you never can be sure that your thread will be waken.

Requirements for the function are specified in section 30.2.4 of the standard. And it specifies that return time should be Ct + Di + Dm where Ct is the time you have specified, Di is a delay induced by overhead oof interrupt, function return and scheduling, and Dm is delay caused by resource contention. In such case Di includes time that passed before you have called sleep_until() and the function returns as soon as it can.

like image 136
Alexey Guseynov Avatar answered Oct 04 '22 14:10

Alexey Guseynov


You're over-analysing this.

Does the standard explicitly say "if the target time is in the past, there will be no block or wait"? No.

Does it go out of its way to explain how a time step will shrink or obliterate the timeout? Yes. Furthermore, it defines these timeouts in terms of relative timeouts.

The intent, I think is fairly clear. It's one of those situations in which you can but have to deduce it from the English wording: if the timeout is immediately satisfied, nothing is going to happen.

More interesting is that it does not appear to be well-defined as to whether there will be an instantaneous lock-and-unlock cycle, in either case.

like image 21
Lightness Races in Orbit Avatar answered Oct 04 '22 15:10

Lightness Races in Orbit