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
#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.