Title
`sleep_for` is not an observable behavior
Status
new
Section
[thread.thread.this]
Submitter
jim x

Created on 2026-07-24.00:00:00 last changed 1 week ago

Messages

Date: 2026-07-24.00:00:00

Consider this example:

#include <iostream>
#include <thread>
#include <chrono>

int main() {
  std::cout << "start to sleep\n";
  std::this_thread::sleep_for(std::chrono::milliseconds(50000)); 
  std::cout << "continue after 50000ms\n";
  return 0;
}

According to [intro.abstract] p8

The following specify the observable behavior of the program:

  • Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.

  • Data is delivered to the host environment to be written into files (See also: ISO/IEC 9899:2024, 7.23.3).

  • The input and output dynamics of interactive devices shall take place in such a fashion that prompting output is actually delivered before a program waits for input. What constitutes an interactive device is implementation-defined.

The specification of `sleep_for` says:

Effects: Blocks the calling thread for the relative timeout ([thread.req.timing]) specified by `rel_time`.

This description of its effect doesn't fall under any of the observable behavior bullets. Does it mean, according to the "as-if" rule, that a conforming implementation can arbitrarily eliminate the call to `sleep_for`? However, this doesn't align with the intent of providing this function in the standard library.

This issue resembles the need to promote "std::filesystem operations" to be observable behaviors, as appealed in LWG 3669. Guaranteed by implementations but not an observable behavior in the abstract machine can result in a conforming implementation eliminating the effect of `sleep_for`, which would make the program terminate quite early, merely holding the difference between two `steady_clock::now` as if `sleep_for` were not eliminated.

History
Date User Action Args
2026-07-24 00:00:00admincreate