What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

C++ Sleep Function: Syntax & Examples (sleep for milliseconds)

  • Jan 04, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
C++ Sleep Function:  Syntax & Examples (sleep for milliseconds)

In this article, we are going to deep dive into the sleep function in C++, its syntax, and examples with code. There are numerous operations provided by the operating system to us, one of them is the sleep() function.

Before going into detail, let's just first cover the basic terminologies we will use in between. But we need to revise some prerequisites like process and threads first.

Process vs Thread

Let's check the easy definitions of both these terms.

The Process is a program in the execution phase or an instance of a program that is being executed or processed is called Process. Thread is a segment of a process or a lightweight process that is managed by the scheduler independently.

Please remember that processes are independent of each other and hence don't share a memory or other resources. On the other hand, threads are interdependent and share memory.

Sleep Function in C++

Sleep function in C++ is used to suspend the execution of a thread or a process for a specified period of time temporarily. Other CPU operations will function adequately but sleep() will delay a specific thread only.

This sleep() function takes one single argument which specifies the time in seconds for which the execution of the thread or the process must be suspended. The thread or process continues to be delayed until the specified time is completed.

Also, note that we can interrupt the sleep() function in between by sending any interrupts to the function. If you are using Windows, must include the header file and if you are using Linux, then must include the header file at the top of your program. 

So, it can be implemented using 2 libraries according to the operating system being used:

#include<windows.h>        // for windows

#include<unistd.h>         // for linux 

 

The execution of the current thread is stopped until at least time_period has passed from now. Other threads continue their execution.

Syntax:

sleep( time_period );    // time_period in seconds

 

Parameters and Return Type:

The sleep() function has only one parameter: time_period, which is the time span after which the calling thread shall resume its execution. Please note that Multi-threading management operations may cause certain delays beyond this.

The sleep returns an Integer. It returns 0 if the function is successfully executed, or else minus the value of the time period returned.

Examples of C++ thread sleep

Given below are the examples of C++ thread sleep:

Example 1 

A C++ program to demonstrate the use of sleep() function:

// Welcome to FavTutor
// 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 10 seconds
sleep(5);

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

 

Output:

Join the Line:
Wait for 5 seconds
It's your time buy ticket

 

In this example, we first included the 2 header files for windows and for Linux users. In the main function, the first cout statements will print first, and then the sleep() function will execute and delays the execution of the process by 5 seconds and after 5 seconds, the third cout will get printed.

Example 2

A C++ program to demonstrate the use of sleep() function:

// Welcome To FavTutor
//the headers iostream and unistd are included to be able to make use of cout and cin statements and sleep() function
#include<iostream> 
#include<unistd.h>
using namespace std;
int main()
{
//The first cout statement is executed
cout<<"Welcome"<<"\n";
//Then the sleep() function is called before executing the next cout statement
sleep(10);
//this cout statement is executed after the sleep function is executed for the speicifed  amount of time
cout<<"to C++";
cout<<endl;
return 0;
}

 

In this example, we included first the required header file, here , first, cout will print initially, and then the sleep() function executes for 10 seconds and after which the second cout will get printed onto the screen.

sleep() for milliseconds

In the 11th version of C++ language, you can do this with standard library facilities:

#include<chrono> 
#include<thread>

 

sleep() function for milliseconds can be implemented as :

std::this_thread::sleep_for(std::chrono::milliseconds(x));

 

Clear and readable, no more need to guess at what units the sleep() function takes.

Conclusion

In this article, we deep dive into the sleep() function in C++ and explored its functionalities with examples. Now, there are various similar functions like sleep() function in C++ like usleep(), sleep_for(), and sleep_until() which you can explore!

Congratulations on getting this far! Now give yourself a pat on the back. Good job!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.