Sleep Functions in C++
C++ provides the functionality of delay or inactive state with the help of the operating system for a specific period of time. Other CPU operations will function adequately but the Sleep() function in C++ will sleep the present executable for the specified time by the thread. It can be implemented using 2 libraries according to the operating system being used:
Sleep
Sleep can suspend execution for time_period where time_period is in seconds by default although we can change it to microseconds.
Syntax:
Parameter: time_period is in seconds it represents the sleep time taken.
Return Type: The return type of sleep function is an integer where if the function is successfully executed then the value returned will be 0, else minus the value of the time period returned.
Example:
Output:
Similar Functions Like sleep in C++
1. usleep():
This function is mostly similar to sleep but can only be used with <unistd.h> library.
Syntax:
Parameter: It takes time_period where time_period is by default in microseconds. 1 second = 10^6 microseconds.
Return Type: Integer where it returns 0 if successful, and (-1 or -exp) if the process failed.
Example:
Output:
2. sleep_for():
Schedules thread for the specified time. It acts like a delay just like sleep function. However, It is possible that threads take more time than the scheduled time due to scheduling activities or can be resource contention delays. Library used <thread>.
Syntax:
Parameter: time_period ( time for which thread is acquired )
Example:
Output:
3. sleep_until():
Blocks the execution of a thread until the sleep_time is finished. However, even when sleep_time has been reached due to scheduling or resource contention delays it could take more time than sleep_time. Library used <thread>.
Syntax:
Parameter: Sleep_time (same time for which thread is blocked for execution)
Example:
Output:
Last updated