The Wayback Machine - https://web.archive.org/web/20240619230159/https://www.geeksforgeeks.org/sleep-function-in-cpp/
Open In App

Sleep Function in C++

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

#include<windows.h>           // for windows

#include<unistd.h>               // for linux 

Sleep can suspend execution for time_period where time_period is in seconds by default although we can change it to microseconds.

Syntax:

sleep( time_period );    // time_period in seconds

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: 

C++
// C++ Program to show how to use
// sleep function
#include <iostream>

// Library effective with Windows
#include <windows.h>

// Library effective with Linux
#include <unistd.h>

using namespace std;

// Driver code
int main()
{
  cout << "Join the Line:\n";
  cout << "Wait for 5 seconds\n";

  // sleep will schedule rest of 
  // activities after 5 seconds
  sleep(5);

  cout << "It's your time buy ticket";
}


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:

 usleep(time_period)   // time_period in microseconds

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: 

C++
// C++ Program to show the 
// use of usleep function
#include <iostream>
#include <unistd.h>

using namespace std;

int main()
{
    cout << "Take your Position\n";

    // sleep for 5 seconds
    cout << "Wait for 5 seconds\n";
    usleep(5000000);

    cout << "Run! Run!";
    return 0;
}


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:

this_<thread_name>::sleep_for(chorno:: time_duration (time_period))         

Parameter:  time_period ( time for which thread is acquired )

Example:

C++
// C++ Program to demonstrate 
// sleep_for()function
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;

// Driver cpde
int main()
{
  cout << "Thread is running\n";
  
  // Thread delayed for 5 seconds
  this_thread::sleep_for(chrono::milliseconds(5000));

  cout << "Thread was acquired for 5 seconds\n";

  return 0;
}


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:

this_<thread_name>::sleep_until(awake_time) 

Parameter:  Sleep_time (same time for which thread is blocked for execution)

Example:

C++
// C++ Program to demonstrate
// sleep_until()
#include <chrono>
#include <iostream>
#include <thread>

// Functioning returning 
// current time
auto now() 
{
  return std::chrono::steady_clock::now(); 
}

// Function calculating sleep time 
// with 2000ms delay
auto awake_time()
{
  using std::chrono::operator"" ms;
  return now() + 2000ms;
}

// Driver code
int main()
{
  std::cout << "Starting the operation .....\n" << 
                std::flush;
  
  // Calculating current time
  const auto start{ now() };

  // using the sleep_time to delay
  // and calculating sleep time
  // using awake_time function
  std::this_thread::sleep_until(awake_time());

  // storing time for printing
  std::chrono::duration<double, std::milli> elapsed{
      now() - start
  };

  // printing waiting time
  std::cout << "Waited for : " << 
                elapsed.count() << " ms\n";
}


Output:



Similar Reads

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 an
3 min read
How to Sleep for Milliseconds in C++?
In programming, sleeping for milliseconds means pausing the execution of the current thread for a specified number of milliseconds, it is often used in cases like creating delays, controlling the execution speed of a program, or simulating a time-consuming operation. In this article, we will learn how to sleep a program for milliseconds in C++. Sle
2 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
How to call function within function in C or C++
When we begin programming in C/C++, we generally write one main() function and write all our logic inside this. This approach is fine for very small programs, but as the program size grows, this become unmanageable. So we use functions. We write code in the form of functions. The main function always acts as a driver function and calls other functi
3 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Difference Between Friend Function and Virtual Function in C++
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and
3 min read
Returning a function pointer from a function in C/C++
In C/ C++, like normal data pointers(int *, char *, etc), there can be pointers to functions. Every function created in a program gets an address in memory since pointers can be used in C/C++, so a pointer to a function can also be created. Syntax: return type (*function_pointer_name) (argument_type_1, argument_type_2, ......, argument_type_n) =
6 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &amp;lt;iostream&amp;gt; using namespace std; class Base { public: void print() { cout &amp;lt;&amp;lt; &amp;quot;Base class print function \n&amp;quot;; } void invoke() { cout &amp;lt;&amp;lt; &amp;quot;Base class invoke function \n&amp;quot;;
2 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Function Pointer to Member Function in C++
In C++, function pointers enable users to treat functions as objects. They provide a way to pass functions as arguments to other functions. A function pointer to a member function is a pointer that points to a non-static member function of a class. In this article, we will learn how to use a function pointer to a member function in C++. Function Po
3 min read
Article Tags :
Practice Tags :