I need to wait for multiple asynchronous tasks but I don't want any blocking behavior, so I checked out this answer and I created a non-blocking async algorithm. Here's my code:
std::vector<std::future<int>> asyncs;
for (int i{0}; i < 4; i++) {
asyncs.push_back(std::async(
std::launch::async,
do_something) // do_something() waits for a random amount of ms and returns the time waited
);
}
for (auto&& fut:asyncs) {
std::cout << "Wait time: " << fut.get() << std::endl;
}
So when I run it I get the following output:
Wait time: 1544
Wait time: 3350
Wait time: 2915
Wait time: 2775
However, I don't know which order they were started in. Was the async that ran for 1544ms
started first or last? Was 2775ms
started second or third? Prior to using non-blocking methods, I would
for (int i{0}; i < 4; i++) int value = asyncs[i].get();
This let me know exactly which task had finished because it was that index in the vector. I am coding for speed so I do not want to search the vector every time an async finishes. And I don't want to do anything sloppy like sending the index as a parameter and returning a tuple
.