So I have print function that I want to execute in 5 seconds. The Problem is that I want everything else in the function. So For example if my code is:
// insert code here...
printf("(5 seconds later) Hello"); /* should be executed in 5 seconds */
printf("heya");
In the main function for example. Now here's the tricky part. While the first line should be executed in 5 seconds, the second line should be executed just like normal if the first line wasn't there at all. So the output would be:
heya
(5 seconds later) Hello
If you familiar with Cocoa or Cocoa Touch, this is exactly how the NSTimer Class works. Using C++, is there a simpler or built in way other than using a thread? If not, how would I go about doing this using multi-threading?
My snap version with boost asio and std::async. No sleeps employed.
Here's how I've solved this problem:
Using
<chrono>
and<thread>
, you can create a pretty rudimentary, but easy one:Another method, which Pubby points out, and has the advantage of automatically waiting for the thread to finish and not stopping if an exception is thrown, is to use
std::async
:The result of
std::async
being stored into a variable means the call will start a new thread to run the function in. If you don't store the result, no new thread. It's one of those new gotchas in the language.Note that it might not be precisely five seconds later when it prints, and there's no syncing of the output, so you might get interleaved output blocks (
printf
is atomic, so the entire output of each call would interleave) if printing more than just a single thing in each thread. Without synchronization, there's no guarantee of which statements happen when, so care should be taken if you do need to be aware of synchronization issues that can arise. For basic purposes, this should work, though.