How to wait for seconds in C++?

C++ wait seconds

There are multiple instances when we need to add delay to our program. For this, C++ provides us with very useful resources to add timed delay, sleep, etc into our program. For instance,  if we are waiting for a job to finish, we want to put something on hold, or we need something to be done periodically, we often need functionalities that can enable us to add timed delays to our program. In this article, we will discuss all the available functionalities and libraries in c++ that can be used to add the delay or wait for seconds in our C++ program. We will discuss sleep, delay, wait, and timer in C++. Let us discuss them one by one, using examples and code so that we can understand how each function can be used to wait for the desired number of seconds in C++.

Wait For Seconds Using The sleep () Function in C++

C++ does not provide us with any sleep function of its own. However, we can use the sleep function provided by operating systems that we are working on in our own program. 

In windows, we can use the sleep() function that is defined in the Windows.h library. On Linux machines, you can use the sleep() function that is defined in the unistd.h library. 

Now before discussing the syntax of the sleep() function and its use cases, we are posed with the problem of writing a cross-platform program that can be executed on Windows as well as Linux operating systems. This issue can be solved by including a few lines of code before the actual code. These lines of code make the suitable choice of the operating system that we are working on and the program is being executed on and it includes the necessary header files. Therefore it saves us a lot of pain by making our program cross-platform.

You should include the following piece of code before the actual code to your program.

The above lines of code first check which operating system you are working on. If you are working on a Windows operating system, it includes windows.h file in your source code. Otherwise, it includes the unistd.h file in your source code. In this way, the program enables you to use the sleep() function to wait for a few seconds in your C++ program irrespective of the operating system you are using.

These lines are important to be included and I advise you not to miss these lines if your program is meant to be run on different platforms i.e. windows as well as Linux. In case you miss it, the program might not execute on either of the platforms. 

Having discussed this, we can move to the prototype and actual implementation of the sleep() function in C++. Below is the prototype of the sleep() function that can be used to wait for the desired number of seconds in C++.

The sleep() function accepts an unsigned integer denoting the number of seconds you want your program to wait. 

The sleep() function also has a return value. It returns 0 if the sleep function completes its execution and the program has waited for the number of seconds you specified. However, if the program is interrupted in between the execution of the sleep() function, it returns the number of seconds left i.e. total number of seconds we wanted the program to wait minus the total number of seconds the sleep() function has executed.   

The sleep() function causes the program to go to a sleep state for the number of seconds that we pass to the function as input argument. The program resumes its execution after the time is over or if an interrupt occurs in between. 

However, due to some priority issues and scheduling by the operating system, the actual wait time may be longer than the number of seconds passed as input.

Now, let us write a simple c++ program to demonstrate how the sleep() function can be used to wait for seconds in C++. 

The output of the above program is given below.

  • In the above program, after including the necessary libraries, we output to the console the first line.
  • After that, the sleep() function is executed which is given 5 as its input argument. Upon execution of the sleep() function, the program waits for 5 seconds before reaching the second output line. You can copy this code and run it on your machine by giving different values as input to the sleep() function. This will help you understand the working of the sleep() function in C++.

Wait For Seconds Using Thread In C++

Beginning with C++11, we are provided with two functions to wait for seconds using threads in C++. As we know that threads are lighter processes running within a process, you can use threads to make the program wait for a few seconds in C++. For this purpose, there are two functions defined in C++ namely sleep_for() function and sleep_until() function. Let us see how we can use these functions to wait for a given number of seconds in C++.

Wait for seconds using sleep_for() function in C++

The sleep_for() function is defined in the <thread> header file. The prototype for the sleep_for() function is as follows.

As you can see, the sleep_for() function accepts the rel_time parameter that indicates the total time for which the thread should sleep. The function does not return any value.

Upon execution, the sleep_for() function makes a thread sleep for at least the duration passed into the function as an input argument. However, due to scheduling activities and resource allocation delays, the sleep can be longer than the time specified by us in the program.

Let us now write a program to understand how we can use the sleep_for() function to wait for seconds in C++. 

The output of the above program is given below.

  • In the above program, after including the necessary header files, we output to the console and then execute the sleep_for() function for the current thread, by giving 5000 milliseconds (i.e. 5 seconds) as input argument. This makes our program sleep for 5 seconds as the current thread is the only thread in our program.
  • We then output a line again to demonstrate that our program actually slept for 5000 milliseconds.  Again, you can copy the above code and run it in your machine to understand the working of the sleep_for() function in a better manner.

Wait for seconds using sleep_until() function in C++

Instead of specifying the total time for waiting, you can use the sleep_until() function to specify till what time the program should sleep. For this, you can use the sleep_until() function in C++. Let us see how we can do this.

The sleep_until() function is defined in the <thread> library. Its prototype is as follows.

The sleep_until() function accepts a parameter named sleep_time that indicates the time until which we want our thread to sleep. The function has no return value. The function makes a thread sleep until the time duration specified by us.

Let us write a simple c++ program to understand the working of the sleep_until() function. 

The output of the above program is given below.

  • In the above program, we have defined a function currentTime() to obtain the current system time. 
  • In the main function, we have displayed the current time. After that, we have created a waitUntil variable that specifies the time until which the program will sleep. Here, we have specified a time 5 seconds ahead of the current system time.
  • After that, the sleep_until() function is executed with waitUntil as the input argument. It causes the program to sleep for 5 seconds. 
  • Finally, we display the time after the thread wakes up. This can be observed in the output, which is 5 seconds later than the previous time. 

Wait for seconds using delay() function in C++

Working of the delay() function is almost similar to the sleep() function. We can use the delay() function to make our programs wait for a few seconds in C++. The delay() function in c++ is defined in the ‘dos.h’ library. Therefore, it is mandatory to include this header file to use the delay function() in our program. The prototype of the delay function is given below.

As we can see from the above prototype, the delay function takes an unsigned integer as a parameter which denotes the number of milliseconds we want our program to wait. Since the return data type is void, the delay function does not return anything.

Let us see a sample program in which we shall see the actual working of the delay function in c++. 

  • The above program, after including necessary header files displays a message to console output.
  • After that, we added a delay of 5000 milliseconds or 5 seconds by passing input arguments to the delay() function. After that, we display another message. 
  • Finally, we add a delay of 5000 milliseconds and display another message in the last line. 

Caution: Since the ‘dos.h’ header file is only valid for DOS-based platforms, our program can only be compiled in the Turbo c++ environment. In other environments such as g++ Linux or equivalent windows environments, the above-written code file can not compile.  

Wait for seconds using the wait() function in C

The wait() function in C is an operating system level call. Upon execution of the wait() function, the operating system blocks the calling process until one of its children returns or a signal is received. We can use this system call in our program when we need our process to wait for a few seconds for some task to finish. The syntax of the wait() system call is given below.

The wait() system call is defined in the wait.h library. Therefore, we need to include the <sys/wait.h> header file in our program to use the wait() system call. The wait system call returns the child process id and also defines a pointer as its parameter that we can use to obtain the exit status of the child. 

If there are no children in the calling process, the wait system call returns -1 immediately. Otherwise, the calling process is blocked until one of the children terminates. 

Let us see a sample program to demonstrate the working of the wait() system call in a C program. 

The output of the program is given below.

  • In the above program, after including necessary header files, we declare a process id variable of type pid_t named as a child to store the child process id. 
  • We then create a child process. If the process is not created successfully,  we exit. 
  • However, if the process is created successfully, we call the wait() function with NULL exit status i.e. with no pointer to store exit status, and receive the return value in child
  • Finally, we print the process ID of the parent and the child which on my machine came out to be as shown in the output snippet. 
  • Note that these IDs can vary every time you run the program and can also vary on different machines. 

Wait For Seconds Using Timer in C++

C++ does not provide any inbuilt library to create a timer for our programs. However, we can create a timer event using system calls in C++. We will see how we can use the sleep() function in C++ to create timer events. 

As we have already discussed the working of the sleep() function, we will directly implement the code to create a timer and will then see how the code works. The following code creates a timer with 1-second intervals for 1 minute. In other words, the program waits for one second, does some work, and then waits again for 1 second. This process continues for 1 minute.

The output of the program is given below.

  • In the above program, we have created a simple timer that runs for 60 seconds and after each time prints the current second.
  • After including the necessary header files (please see the ‘sleep’ section for info on code and sleep function) we define a variable counter which is initialized with a value of 60 to count to 60 seconds. 
  • In the loop, we then display the counter each time and then sleep for 1 second. This makes the timer run for 60 seconds. 
  • The flush function is used to de-buffer the console output without which the timer may not display the contents properly.

Conclusion

Sometimes, it is very important to introduce timed delays into our programs when we want our programs to wait for a few seconds in C++. There are multiple ways to do this and we have discussed many ways to do so. However, each of the ways has its own capabilities and shortcomings and we have discussed that too. It is advisable to understand each of the ways first and then implement them into your programs. For example, with the sleep() function, not including the correct header file corresponding to the operating system being used, is a trap that we must avoid. This article gives a solid understanding of different ways to make our programs wait. Finally, we have discussed a method to implement a timer in our program in C++.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *