| by Arround The Web | No comments

What is Sleep Function in C++

In C++, while dealing with multiple programs\threads, users often need to pause\block some tasks to minimize the usage of the CPU, simulate time-consuming tasks, and control the speed of the program execution. Then, resume them due to the usage of the same resource simultaneously. For that particular purpose, C++ provides numerous functionalities for delaying or pausing the execution of programs\threads that are trying to access the same resource synchronously, and the “sleep()” function is one of them.

Quick Outline

What is the sleep() Function in C++?

The “sleep()” is the built-in function of C++ used to sleep the particular thread of the C++ with the help of the operating system for a specific interval of time that is executing in the specific process. Additionally, it is often utilized in multi-threading environments. As we described above, this function is mainly used when more than one thread tries to access the same resources. After suspending the execution of the particular program for a given period of time, it resumes the execution from the same point where it is suspended.

Difference Between Process and Thread

Before moving forward, first, understand the difference between process and thread. The process is a program that is currently executing. In simple words, an instance of a program that is being proceeded is known as a Process. Additionally, it does not share the resources. On the other hand, the thread is a segment of a process that can be independently scheduled for execution and share the memory.

Syntax of sleep() Function in C++

The general syntax of the “sleep()” function is stated below:

sleep(particular_time_interval)

Parameter
The sleep() function takes a single parameter that represents the period of time for which the current thread requires delay or pause.

Return Type
It returns an integer value when the specified sleep time of the thread is completed successfully.

Exceptions
The C++ sleep() doesn’t throw any exceptions.

Note: The “sleep()” function takes sleep duration in seconds. However, time intervals can be specified in hours, minutes, seconds, milliseconds, microseconds, or nanoseconds, and depending on that we have different functions that can sleep the particular program.

What are the Applications of sleep() Function in C++?

To use “sleep()” efficiently is more important than just understanding its syntax. Some use cases of the sleep() function are listed below:

  • To temporarily delay or pause the program can help users in debugging time-dependent features.
  • To minimize CPU usage while performing writing/reading operations, sleep() can be used.
  • The sleep() function is mostly utilized when multiple threads are trying to use a similar resource.
  • In multi-threaded applications, users can put one thread to sleep for completing the executions of another thread synchronously.

How to Use the sleep() Function in C++?

To use the sleep() for delaying the execution of the thread or process for a particular time duration in C++, check out the following examples.

Example 1: How to Use sleep() Function to Pause Current Thread in C++?

In this example, we will use the sleep() function to delay the present thread execution for a particular time duration and then resume it. Let’s check out the below-given code block:

#include <iostream>
#include <unistd.h>

int main()
{
    std::cout << "Wait for 3 seconds\n";
    sleep(3);
    std::cout <<"Welcome to linuxhint.com";
    return 0;
}

Here:

  • First, added the required header files, “<iostream>” for accessing the input\output functionalities and “<unistd.h>” for sleep() function respectively.
  • Next, inside the “main()” function, we used the “cout” statement that will print the first output statement on the console.
  • Then, invoked the sleep() to delay the execution of the currently running process by “3” seconds.
  • After that, the second “cout” statement will get printed.

Check out the following output that we will get after executing the previously provided code:

Example 2: How to Use sleep() Function to Delay Process Execution in C++ Loop?

You can also pause any running process for a particular time duration using the sleep() function. For a better understanding, move forward to the below code block:

#include <iostream>
#include <unistd.h>
using namespace std;

int main() {
  char arr[20];
  cout << "Enter Your Name: ";
  cin.getline(arr,20);
  cout << "Your Name is:\n";
 
  for (int  x = 0; arr[x]!='\0'; x++)
  {
    cout << arr[x]<<endl;
    sleep(2);
  }
  cout << "Loop has been executed successfully With 2 seconds delay.";
  return 0;
}

According to the above-described code:

  • Initially, we have added the necessary header files along with the standard namespace.
  • We declared the character type array as having the size of “20”.
  • Then, used the “cout” statement to print the message on the console.
  • Next, invoked the “getline()” method to read a string or a line from an input stream and then display the user’s input using the output stream.
  • Afterward, we called the “sleep()” function inside the “for” loop where we passed the array without accepting the null value and specified the “2” seconds for the delay.
  • Lastly, used the output stream to print the successful execution message.

Output

What are the Similar Functions of sleep() in C++?

In C++, there are some other functions that are similar to “sleep()”, which are listed below:

  • usleep() Function
  • std::this_thread::sleep_for() Function
  • std::this_thread::sleep_until() Function

Let’s move ahead and check them out one by one!

usleep() Function in C++

The working of the “usleep()” function is the same as the “sleep()” function used to delay the execution of the calling thread. Additionally, the “<unistd.h>” header is required for this function.

Syntax
Here is the syntax of the above-described function:

usleep(microseconds)

Parameters
It takes one argument that indicates the time interval only in microseconds(1 second = 1000000).

Return Value
This function returns “0” if the thread is executed successfully.

Example
Here, first, we added the required header files. Then, we used the output stream to show the output message on the console. Next, we invoked the “usleep()” function and passed the program pausing time period in microseconds. Then, we used another “cout” statement that will be executed after the sleep function is executed for a particular time interval:

#include <iostream>
#include <unistd.h>

int main()
{
    std::cout << "System is on sleep mode, please wait for 4 seconds...\n";
    usleep(4000000);
    std::cout <<"Welcome to linuxhint.com";
    return 0;
}

As you can see, when the sleep() function is called, it pauses the process for a specific time period and then resumes it:

this_thread::sleep_for() Function in C++

The “sleep_for()” function pauses the currently running threads at least for the provided time duration that is referred to as the “sleep()” function. Moreover, this function is defined in the <thread> header, and its unit of time in hours, minutes, seconds, milliseconds, or microseconds.

Note: Because of resource contention delays or scheduling activities, this function may block threads for a longer duration than a specified time interval.

Syntax

this_<thread_name>::sleep_for(chrono::<unit_of_time(time_period)>)

In the above-stated syntax:

  • “<thread_name>” represents the currently executed thread.
  • “chrono” is the measure of the exact time or quantitative time.
  • “<unit_of_time>” indicates the time units, such as seconds, mili\microseconds.
  • “<time_period>” represents the particular time period.

Parameters
The “sleep_for()” function takes only one argument.

Return Value
None

Exceptions
The C++ sleep_for() throws an exception during thread\process execution by providing a time duration, clock, or time unit.

Example
In the following example code, first, we defined the necessary header files, such as “<iostream>”, “<thread>”, and “<chrono>”. Next, used the “while” loop and declared the character type array as having the size of “20”. Afterward, called the “getline()” method to reads an input string or a line and then shows the user’s input using the output stream. Then, we showed a program delay message on the screen. Finally, invoked the “sleep_for()” function to block the currently executing program for “4” seconds. Afterward, the program will resume, and the next output displayed on the console through the output stream:

#include <iostream>
#include <chrono>
#include <thread>

int main() {

while (true) {
    char arr[20];
    std::cout << "Employee Name: ";
    std::cin.getline(arr, 20);
    std::cout << "\nYour Provided Employee Name is: " << arr <<"\n";
 
    std::cout << "Program will sleep for 4 seconds, wait...:\n";
    std::this_thread::sleep_for(std::chrono::seconds(4));
    std::cout << "Return back to your program\n\n";
}

}

Output

this_thread::sleep_until() Function in C++

The “sleep_until()” function is also utilized for pausing the thread\process until the defined time interval inside the “<thread>” header and its unit of time in hours, minutes, seconds, milliseconds, or microseconds. Moreover, like other functions, it may pause for a longer time duration than the provided because of scheduling activities.

Syntax

this_<thread_name>::sleep_until(time_period)

Here:

  • “<thread_name>” indicates the present running thread.
  • “<time_period>” represents the particular time period.

Parameter
Like other similar functions of sleep(), it also takes one parameter.

Return Type
None

Exceptions
Any exception thrown by the provided time duration, or clock.

Example
Here, we have specified the required header files and then used the “std::chrono::steady_clock::now()” to get the current time and date of the system. Then, saved it into the auto type variable named “nxt_iter”. Next, inside the “while” loop, we define the time interval for the next proceeding iteration of the loop which is “5000000” microseconds, and saved it into the “nxt_iter” variable by using the compound assignment operator “+=”. Then, we displayed the output message utilizing the “cout” stream. After that, used the “sleep_until()” and passed the “nxt_iter” variable as an argument:

#include <iostream>
#include <chrono>
#include <thread>

int main() {
    auto nxt_iter = std::chrono::steady_clock::now();

    while (true) {
        nxt_iter += std::chrono::microseconds(5000000);
        std::cout << "Welcome to LinuxHint\n";
        std::cout << "Please wait for 5 microseconds...\n\n";
        std::this_thread::sleep_until(nxt_iter);
    }
}

The above-discussed code retrieves the following output:

That’s it! We have provided detailed information about the “sleep()” function in C++.

Bottom Line

In C++, the “sleep()” function is used to delay the execution of any thread\process for a specified time interval. Mainly, it is used for minimizing the usage of the CPU, simulating time-consuming tasks, and controlling the speed of the program execution. There are some other functions that work like the “sleep()” function such as “usleep()”, “sleep_for()”, and “sleep_until()”. In this tutorial, we have described the “sleep()” function with the aid of examples.

Share Button

Source: linuxhint.com

Leave a Reply