C++ Sleep: How To Use The Sleep Function in C++ Programs

This C++ Sleep tutorial will discuss the Sleep Function in C++ & see how to put a thread to sleep. We will also learn about the other functions viz. usleep:

Any computer program that is a process, task or thread may ‘sleep’ or go into an inactive state for a specific time. The execution is suspended, for this period of time. The execution will be resumed back when the time interval of sleep expires or a signal or interrupt causes the execution to resume.

To put a program (task, process or thread) to sleep we make use of a sleep system call. A typical sleep system call takes the time as the parameter that indicates how much time the program needs to sleep or remain inactive.

=> Check The Complete C++ Training Series Here.

C++ Sleep () function

We also have usleep () and thread:: sleep functions which we will discuss in this tutorial. The time provided is mostly in milliseconds, microseconds or seconds and depending on that we have various functions that can put the program to sleep.

Sleep () Function

C++ language does not provide a sleep function of its own. However, the operating system's specific files like unistd.h for Linux and Windows.h for Windows provide this functionality.

When we use the Linux or UNIX operating system, we need to include “unistd.h” header file in our program to use the sleep () function.

While using the Windows operating system, we have to include “Windows.h” header to use the sleep () function. So in order to write a cross-platform program, we can have the code as shown below so that either of the headers will be used.

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

The sleep function is described below:

Function prototype:

unsigned sleep(unsigned seconds);

Parameters:

seconds => Time period in seconds for which execution of the program is suspended

Return value:

0 => If sleep returns as the requested time has elapsed.

If sleep is interrupted by a signal then an unslept amount (requested time period specified minus the actual time elapsed) is returned.

Description:

The sleep () function causes the program or the process in which it is called, to suspend its execution temporarily for a period of time in seconds specified by the function parameter. Execution is suspended until the requested time is elapsed or a signal or an interrupt is delivered to the function.

However, if the system has scheduled any other activity, then the suspension time may be longer.

Given below is a C++ program that uses the sleep function between two cout statements.

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
  cout << "Hello ";
  cout.flush();
  sleep(10);
  cout << "World";
  cout << endl;
  
  return 0;
}

Output:

Hello World

In the above program, we give a sleep command with 10 seconds period after printing “Hello”. The compiler waits for 10 seconds after printing “Hello” and then prints the “World”.

Note: Readers should execute this program to actually understand the working of the sleep command

Usleep () Function

The header “unistd.h” provides yet another function “usleep()” that can suspend the execution of a program for a specified period of time. The working is similar to sleep () function described already.

Function prototype: int usleep(useconds_t useconds);

Parameters: useconds => Number of microseconds for which the execution is suspended

Return value:

0 => Usleep has returned successfully.
-1 &errno => Function failed.

Description:

The function usleep () suspends the execution of calling thread for useconds microseconds or until the signal is delivered to the thread that interrupts the execution.

The granularity of the timer values used in the usleep function may be implementation-specific. If we need finer granularity than the one specified by the implementation, then the actual timer value is rounded up to the next supported value.

Given below is an example to demonstrate the usleep () function.

#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;
int main()
{
  cout << "Hello ";
  cout.flush();
  usleep(10000);
  cout << "World";
  cout << endl;
  
  return 0;
}

Output:

Hello World

As shown in the above output, we specify the time period as 10000 microseconds for usleep function and just like the previous program using sleep function, we print the “Hello World” string.

Thread Sleep (sleep_for & sleep_until)

C++ 11 provides specific functions to put a thread to sleep.

There are two functions:

Std::this_thread::sleep_for

Function prototype:

template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );

Parameters: sleep_duration => Time duration to sleep

Return Value: none

Description: The sleep_for () function is defined in the header <thread>. The sleep_for () function blocks the execution of the current thread at least for the specified time i.e. sleep_duration.

This function may block for a longer duration than a specified time due to scheduling activities or resource contention delays.

A C++ example demonstrating the usage of sleep_for is given below:

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
 
int main()
{
    cout << "Hello I'm waiting...." << endl;
    this_thread::sleep_for(chrono::milliseconds(20000) );
    cout << "Waited 20000 ms\n";
}

Output:

Hello I'm waiting….
Waited 2000 ms

sleep_for

In the above program, we have a specified sleep duration of 20000 milliseconds. This means that the thread will block for 20000 milliseconds before resuming the operation.

Std::this_thread::sleep_until

Function prototype:

template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );

Parameters: sleep_time => Time duration until which the thread is to be blocked.

Return Value: none

Description: This function is defined in the <thread> header. The sleep_until () function blocks the execution of a thread until the sleep_time is elapsed. Like the other functions, this function may also block for a longer duration than a specified time due to scheduling activities or resource contention delays.

A C++ program for sleep_until function is given below.

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void current_time_point(chrono::system_clock::time_point timePt)
{
	time_t timeStamp = chrono::system_clock::to_time_t(timePt);
	cout << std::ctime(&timeStamp) << endl;
}
 
void threadFunc()
{
 	cout<<"Current Time :: ";
	current_time_point(chrono::system_clock::now());
 
	chrono::system_clock::time_point timePt =
			chrono::system_clock::now() + chrono::seconds(60);
 
	cout << "Sleeping Until :: "; 
	current_time_point(timePt);
 
 	this_thread::sleep_until(timePt);
 
	cout<<"Woke up...Current Time :: ";
	current_time_point(chrono::system_clock::now());
}
int main()
{
std::thread th(&threadFunc);
th.join();
return 0;
}

Output:

Current Time :: Thu Sep 19 12:52:01 2019
Sleeping Until:: Thu Sep 19 12:53:01 2019
Woke up…Current Time :: Thu Sep 19 12:53:01 2019

sleep_until function

In this program, we make the thread sleep for 60 seconds i.e. 1 minute. Once 1 minute is complete; thread wakes up and prints the current time.

Frequently Asked Questions

Q #1) What does sleep () do in C++?

Answer: Sleep () function suspends the execution of the program for a specified period of time. This time period is specified as an argument to the sleep () function.

Q #2) What is the header file for sleep in C++?

Answer: The header for sleep is “unistd.h” for LINUX/UNIX Operating system and “Windows.h” for the Windows Operating system. For thread sleep that uses ‘sleep_for’ and ‘sleep_until’ functions, <thread> header is used.

Q #3) What is the use of #include Unistd H?

Answer: The header ‘Unistd.h’ is the header that defines the sleep () function to suspend the execution of the program.

Conclusion

In this tutorial for sleep () function, we have discussed the sleep function and usleep () function which is the same as the sleep and thread sleep functions, sleep_for and sleep_until. Sleep () and usleep () functions are same except for the time unit used to specify the sleep time.

In sleep () function, the time is specified in seconds, while in usleep () function, the time is specified in microseconds. The thread functions sleep_for () suspends the thread execution for a specific time period provided as an argument. The second thread function sleep_until () suspends the execution of the thread until a specified time has elapsed.

All the sleep functions discussed may take a longer time to return depending on scheduling or other resource-specific delays.

=> Read Through The Popular C++ Training Series Here.