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++?
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.
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.
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.
#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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With