std::this_thread::sleep_for() is a C++ standard library function that suspends the execution of the current thread for a specified duration. It is defined in the <thread> header and works together with the <chrono> library to specify time intervals.
- Pauses only the calling thread, allowing other threads to continue execution.
- Supports time durations such as milliseconds, seconds, minutes, and hours using <chrono>.
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
int main()
{
cout << "Start\n";
this_thread::sleep_for(chrono::seconds(2));
cout << "End\n";
return 0;
}
Output
Start End
Explanation: The main thread pauses for 2 seconds before printing "End".
Syntax
std::this_thread::sleep_for(duration);
- Parameter: duration - A std::chrono::duration object specifying how long the current thread should sleep.
- Return Value: This function does not return any value.
Working of sleep_for()
The sleep_for() function suspends only the thread from which it is called.
- If called inside main(), the main thread pauses.
- If called inside a worker thread, only that thread pauses while other threads continue executing.
- Execution automatically resumes after the specified duration expires.
Example: Sleeping the Main Thread
#include <iostream>
#include <thread>
using namespace std;
int main()
{
// Displaying a Statement
cout << "1st Line" << endl;
// Halting the execution for 10000ms (milliseconds) or
// 10 seconds
std::this_thread::sleep_for(10000ms);
// Displaying the line after waiting for 10 seconds
cout << "2nd Line" << endl;
return 0;
}
Output
Explanation: The main thread sleeps for 3 seconds before executing the next statement.
Specifying the Sleep Duration
The duration is usually specified using the utilities provided by the <chrono> library. Some commonly used duration types are:
| Duration | Example |
|---|---|
| Nanoseconds | chrono::nanoseconds(100) |
| Microseconds | chrono::microseconds(500) |
| Milliseconds | chrono::milliseconds(250) |
| Seconds | chrono::seconds(5) |
| Minutes | chrono::minutes(2) |
| Hours | chrono::hours(1) |
For convenience, C++ also provides duration literals (when enabled), such as:
using namespace std::chrono_literals;
this_thread::sleep_for(500ms);
this_thread::sleep_for(2s);
Advantages of sleep_for()
The sleep_for() function offers several benefits:
- Provides a portable way to pause thread execution.
- Suspends only the current thread instead of all threads.
- Useful for delays, scheduling, and synchronization.
Limitations of sleep_for()
Despite its usefulness, sleep_for() has some limitations:
- The actual sleep time may be slightly longer than requested due to operating system scheduling.
- It should not be used for precise real-time timing.
- Excessive use can reduce application responsiveness.