Use std::this_thread::sleep_for Method to Sleep in C++
The sleep_for method in the thread header file suspends the program’s execution for a certain period. The method also requires the presence of the chrono header file if chrono::duration is used. Unlike other suspending functions like sleep or usleep, the method does not suspend the execution of the whole program. i.e., the method is thread based and requires a thread to work on. Hence, if the motive is to halt the execution of the whole program, then this_thread is used inside the main function. But if the method is called within a thread, it halts the thread’s execution instead of the whole program.
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );
sleep_duration - Time duration of program suspension (halt)
The argument to the function could also be an integer with a time fraction. i.e., if 10ms is passed as an argument, the thread would be suspended for 10 milliseconds.
Suspending execution using the sleep_for function
The sleep_for method requires a thread to work on. For demonstration, the whole program would be halted. In this case, the sleep_for method would be inside the main function and would have the following syntax:
Where this_thread denotes the execution of the current thread (from which the method is called) is to be halted. When used inside the main function, the methods work similarly to the sleep function in the stdlib header file.
Explanation: Firstly, the chrono header file and the thread header file are imported. Then a string is displayed on the console. Then the sleep_for method is called with the argument 10000ms. Where 10000ms is a contraction of 10000 Milliseconds, which equates to 10 seconds. Hence, the function suspends program execution for 10 seconds once it is called. After which, another line is displayed (after 10 seconds*).
Optionally, one could also send chrono::duration<Rep, Period> as an argument. The latter one allowing more readability and ease of representation. That functionality could be incorporated by including the chrono header file.
* The effect could be verified at the end when the program execution time is displayed by the compiler, which is 10.084 seconds, whereas a trivial program like this (without the sleep_for function call) would execute in under 1 second. This could be used to verify the functionality of the program.