I have been struggling for days to come up with a mechanism for launching a few timers and not having it clock the main program execution. Combinations of .join() and .detach(), wait_until(), etc
What I have is a vector of std::thread and I want to:
- execute the first position
- wait for it to finish
- execute the next position
- wait for it to finish
meanwhile the rest of my app is running along, users clicking things, etc. Everything I come up with seems to either:
- block the main program from running while the timers are going
or
- detach from the main thread but then the timers run concurrently, how I want one after the previous one has finished.
I even posted: C++11 std::threads and waiting for threads to finish but no resolution that I can seem to make sense of either.
should I be using std::launch::async maybe?
EDIT: I am not sure why this is so hard for me to grasp. I mean video games do this all the time. Take Tiny Tower for example. You stock your floors and each one of those operations has a delay from when you start the stock, until when that item is stocked and it triggers a HUD that pops up and says, "Floor is now stocked". Meanwhile the whole game stays running for you to do other things. I must be dense because I cannot figure this out.
This snippet of code will execute a
std::vectorof nullary tasks in a separate thread.this should run each of the tasks in series outside the main thread, and return a
std::futurethat contains the timing results.If you want the timing results in smaller chunks (ie, before they are all ready), you'll have to do more work. I'd start with
std::packaged_taskand return astd::vector<std::future< timing >>and go from there.The above code is untested/uncompiled, but shouldn't have any fundamental flaws.
You'll note that the above does not use
std::thread.std::threadis a low level tool that you should build tools on top of, not something you should use directly (it is quite fragile due to the requirement that it bejoined ordetached prior to destruction, among other things).While
std::asyncis nothing to write home about, it is great for quick-and-dirty multiple threading, where you want to take a serial task and do it "somewhere else". The lack of decent signaling viastd::futuremakes it less than completely general (and is a reason why you might want to write higher level abstractions aroundstd::thread).Here is one that will run a sequence of tasks with a minimum amount of delay between them:
which should make the helper
asyncthread sleep for (at least as long as) the durations you use before running each task. As written, time taken to execute each task is not counted towards the delays, so if the tasks take longer than the delays, you'll end up with the tasks running with next to no delay between them. Changing that should be easy, if you want to.