What is Sleep Function in C++

In C++, whereas coping with a number of programsthreads, customers usually have to pauseblock some duties to reduce the utilization of the CPU, simulate time-consuming duties, and management the velocity of this system execution. Then, resume them because of the utilization of the identical useful resource concurrently. For that specific goal, C++ offers quite a few functionalities for delaying or pausing the execution of programsthreads which can be making an attempt to entry the identical useful resource synchronously, and the “sleep()” operate is one among them.

Fast Define

What’s the sleep() Operate in C++?

The “sleep()” is the built-in operate of C++ used to sleep the actual thread of the C++ with the assistance of the working system for a particular interval of time that’s executing within the particular course of. Moreover, it’s usually utilized in multi-threading environments. As we described above, this operate is principally used when multiple thread tries to entry the identical assets. After suspending the execution of the actual program for a given time frame, it resumes the execution from the identical level the place it’s suspended.

Distinction Between Course of and Thread

Earlier than transferring ahead, first, perceive the distinction between course of and thread. The method is a program that’s at present executing. In easy phrases, an occasion of a program that’s being proceeded is called a Course of. Moreover, it doesn’t share the assets. Then again, the thread is a phase of a course of that may be independently scheduled for execution and share the reminiscence.

Syntax of sleep() Operate in C++

The overall syntax of the “sleep()” operate is said under:

sleep(particular_time_interval)

Parameter
The sleep() operate takes a single parameter that represents the time frame for which the present thread requires delay or pause.

Return Sort
It returns an integer worth when the desired sleep time of the thread is accomplished efficiently.

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

Be aware: The “sleep()” operate takes sleep period in seconds. Nevertheless, time intervals will be laid out in hours, minutes, seconds, milliseconds, microseconds, or nanoseconds, and relying on that we now have completely different capabilities that may sleep the actual program.

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

To make use of “sleep()” effectively is extra necessary than simply understanding its syntax. Some use circumstances of the sleep() operate are listed under:

  • To briefly delay or pause this system will help customers in debugging time-dependent options.
  • To attenuate CPU utilization whereas performing writing/studying operations, sleep() can be utilized.
  • The sleep() operate is generally utilized when a number of threads try to make use of an identical useful resource.
  • In multi-threaded functions, customers can put one thread to sleep for finishing the executions of one other thread synchronously.

How you can Use the sleep() Operate in C++?

To make use of the sleep() for delaying the execution of the thread or course of for a specific time period in C++, try the next examples.

Instance 1: How you can Use sleep() Operate to Pause Present Thread in C++?

On this instance, we are going to use the sleep() operate to delay the current thread execution for a specific time period after which resume it. Let’s try the below-given code block:

#embrace <iostream>
#embrace <unistd.h>

int major()
{
    std::cout << “Look ahead to 3 secondsn;
    sleep(3);
    std::cout <<“Welcome to linuxhint.com”;
    return 0;
}

Right here:

  • First, added the required header recordsdata, “<iostream>” for accessing the inputoutput functionalities and “<unistd.h>” for sleep() operate respectively.
  • Subsequent, contained in the “major()” operate, we used the “cout” assertion that may print the primary output assertion on the console.
  • Then, invoked the sleep() to delay the execution of the at present operating course of by “3” seconds.
  • After that, the second “cout” assertion will get printed.

Try the next output that we are going to get after executing the beforehand offered code:

Instance 2: How you can Use sleep() Operate to Delay Course of Execution in C++ Loop?

It’s also possible to pause any operating course of for a specific time period utilizing the sleep() operate. For a greater understanding, transfer ahead to the under code block:

#embrace <iostream>
#embrace <unistd.h>
utilizing namespace std;

int major() {
  char arr[20];
  cout << “Enter Your Identify: “;
  cin.getline(arr,20);
  cout << “Your Identify is:n;
 
  for (int  x = 0; arr[x]!=; x++)
  {
    cout << arr[x]<<endl;
    sleep(2);
  }
  cout << “Loop has been executed efficiently With 2 seconds delay.”;
  return 0;
}

In accordance with the above-described code:

  • Initially, we now have added the required header recordsdata together with the usual namespace.
  • We declared the character sort array as having the dimensions of “20”.
  • Then, used the “cout” assertion to print the message on the console.
  • Subsequent, invoked the “getline()” technique to learn a string or a line from an enter stream after which show the consumer’s enter utilizing the output stream.
  • Afterward, we referred to as the “sleep()” operate contained in the “for” loop the place we handed the array with out accepting the null worth and specified the “2” seconds for the delay.
  • Lastly, used the output stream to print the profitable execution message.

Output

What are the Comparable Capabilities of sleep() in C++?

In C++, there are another capabilities which can be just like “sleep()”, that are listed under:

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

Let’s transfer forward and test them out one after the other!

usleep() Operate in C++

The working of the “usleep()” operate is identical because the “sleep()” operate used to delay the execution of the calling thread. Moreover, the “<unistd.h>” header is required for this operate.

Syntax
Right here is the syntax of the above-described operate:

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

Return Worth
This operate returns “0” if the thread is executed efficiently.

Instance
Right here, first, we added the required header recordsdata. Then, we used the output stream to indicate the output message on the console. Subsequent, we invoked the “usleep()” operate and handed this system pausing time interval in microseconds. Then, we used one other “cout” assertion that can be executed after the sleep operate is executed for a specific time interval:

#embrace <iostream>
#embrace <unistd.h>

int major()
{
    std::cout << “System is on sleep mode, please anticipate 4 seconds…n;
    usleep(4000000);
    std::cout <<“Welcome to linuxhint.com”;
    return 0;
}

As you’ll be able to see, when the sleep() operate is named, it pauses the method for a particular time interval after which resumes it:

this_thread::sleep_for() Operate in C++

The “sleep_for()” operate pauses the at present operating threads not less than for the offered time period that’s known as the “sleep()” operate. Furthermore, this operate is outlined within the <thread> header, and its unit of time in hours, minutes, seconds, milliseconds, or microseconds.

Be aware: Due to useful resource rivalry delays or scheduling actions, this operate could block threads for an extended period than a specified time interval.

Syntax

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

Within the above-stated syntax:

  • “<thread_name>” represents the at present executed thread.
  • “chrono” is the measure of the precise time or quantitative time.
  • “<unit_of_time>” signifies the time items, equivalent to seconds, milimicroseconds.
  • “<time_period>” represents the actual time interval.

Parameters
The “sleep_for()” operate takes just one argument.

Return Worth
None

Exceptions
The C++ sleep_for() throws an exception throughout threadprocess execution by offering a time period, clock, or time unit.

Instance
Within the following instance code, first, we outlined the required header recordsdata, equivalent to “<iostream>”, “<thread>”, and “<chrono>”. Subsequent, used the “whereas” loop and declared the character sort array as having the dimensions of “20”. Afterward, referred to as the “getline()” technique to reads an enter string or a line after which exhibits the consumer’s enter utilizing the output stream. Then, we confirmed a program delay message on the display. Lastly, invoked the “sleep_for()” operate to dam the at present executing program for “4” seconds. Afterward, this system will resume, and the following output displayed on the console via the output stream:

#embrace <iostream>
#embrace <chrono>
#embrace <thread>

int major() {

whereas (true) {
    char arr[20];
    std::cout << “Worker Identify: “;
    std::cin.getline(arr, 20);
    std::cout << nYour Offered Worker Identify 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 again to your programnn;
}

}

Output

this_thread::sleep_until() Operate in C++

The “sleep_until()” operate can be utilized for pausing the threadprocess till the outlined time interval contained in the “<thread>” header and its unit of time in hours, minutes, seconds, milliseconds, or microseconds. Furthermore, like different capabilities, it might pause for an extended time period than the offered due to scheduling actions.

Syntax

this_<thread_name>::sleep_until(time_period)

Right here:

  • “<thread_name>” signifies the current operating thread.
  • “<time_period>” represents the actual time interval.

Parameter
Like different comparable capabilities of sleep(), it additionally takes one parameter.

Return Sort
None

Exceptions
Any exception thrown by the offered time period, or clock.

Instance
Right here, we now have specified the required header recordsdata after which used the “std::chrono::steady_clock::now()” to get the present time and date of the system. Then, saved it into the auto sort variable named “nxt_iter”. Subsequent, contained in the “whereas” loop, we outline the time interval for the following continuing iteration of the loop which is “5000000” microseconds, and saved it into the “nxt_iter” variable through the use of the compound task operator “+=”. Then, we displayed the output message using the “cout” stream. After that, used the “sleep_until()” and handed the “nxt_iter” variable as an argument:

#embrace <iostream>
#embrace <chrono>
#embrace <thread>

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

    whereas (true) {
        nxt_iter += std::chrono::microseconds(5000000);
        std::cout << “Welcome to LinuxHintn;
        std::cout << “Please wait for five microseconds…nn;
        std::this_thread::sleep_until(nxt_iter);
    }
}

The above-discussed code retrieves the next output:

That’s it! We now have offered detailed details about the “sleep()” operate in C++.

Backside Line

In C++, the “sleep()” operate is used to delay the execution of any threadprocess for a specified time interval. Primarily, it’s used for minimizing the utilization of the CPU, simulating time-consuming duties, and controlling the velocity of this system execution. There are another capabilities that work just like the “sleep()” operate equivalent to “usleep()”, “sleep_for()”, and “sleep_until()”. On this tutorial, we now have described the “sleep()” operate with assistance from examples.

Data: This publish is rewritten with inspiration from the unique URL. Please click on on the supply hyperlink to learn the unique publish

Supply Hyperlink : https://linuxhint.com/use-sleep-method-in-cpp/

Related Articles

Back to top button
close