CKTIS / C++
std::this_thread::sleep_for — pause the current thread
std::this_thread::sleep_for blocks the calling thread for a relative interval expressed as std::chrono::duration. It neither creates a thread nor synchronizes access to data. Returning may take longer than the requested interval.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <thread>
#include <chrono>
template<class Rep, class Period>
void std::this_thread::sleep_for(
const std::chrono::duration<Rep, Period>& rel_time);std::this_thread::sleep_for, declared in <thread>, blocks the thread that calls it. Its rel_time argument is a duration of type std::chrono::duration<Rep, Period>; include <chrono> to express time units. The function returns void. Calling it in main therefore pauses the thread executing main, rather than creating a background task.
This is a relative wait: std::chrono::milliseconds{20} specifies an interval, not a completion time point. For a positive duration, do not expect a return at exactly that interval: thread scheduling and resource contention can extend the wait. The standard recommends that implementations measure it with a steady clock, but does not mandate using std::chrono::steady_clock. In contrast, std::this_thread::sleep_until accepts a time point.
The function provides no synchronization: merely waiting neither proves that another thread has finished nor makes shared data safe. Use an appropriate synchronization mechanism for coordination instead of assuming that a chosen pause is sufficient. The specification permits timeout-related exceptions; the standard clock and time types supplied by the implementation do not throw them.
The example performs one pause between two output operations. The expected output has a fixed order, but exact execution time is not part of the result. The source is an evolving working draft, not a frozen C++23 edition.
Examples
#include <chrono>
#include <iostream>
#include <thread>
int main() {
std::cout << "Before\n";
std::this_thread::sleep_for(std::chrono::milliseconds{20});
std::cout << "After\n";
}
Result
Before After
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.