Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause program execution for 5 seconds in c++

Tags:

c++

I want to pause the execution of c++ program for 5 seconds. In android Handler.postDelayed has the required functionality what I am looking for. Is there anything similar to that in c++?

like image 838
charlotte Avatar asked May 12 '14 12:05

charlotte


People also ask

How do you pause in C?

h> pause (); If the process receives a signal whose effect is to terminate it (typically by typing Ctrl + C in the terminal), then pause will not return and the process will effectively be terminated by this signal.

What is sleep () in C?

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval.

How do you pause a program for a few seconds in C++?

Wait for seconds using delay() function in C++ 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.


2 Answers

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

int main()
{
    std::cout << "Hello waiter" << std::endl;
    std::chrono::seconds dura( 5);
    std::this_thread::sleep_for( dura );
    std::cout << "Waited 5s\n";
}

this_thread::sleep_for Blocks the execution of the current thread for at least the specified sleep_duration.

like image 72
const_ref Avatar answered Oct 07 '22 16:10

const_ref


You can do this on the pure C level, because C api calls are usable also from C++. It eliminiates the problem if you actual c++ library didn't contained the needed std:chrono or std::this_thread (they differ a little bit).

The C api of most OSes contains some like a sleeping function, although it can be also different. For example, on posixen, there is the sleep() API call in the standard C library, and you can use this from C++ as well:

#include <unistd.h>

int main() {
   sleep(5);
   return;
}

Or you can use usleep() is you want a better precision as seconds. usleep() can sleep for microsecond precision.

On windows, you can use the Sleep(int usec) call, which is with big 'S', and uses milliseconds.

like image 33
peterh Avatar answered Oct 07 '22 16:10

peterh