I try to parallelize calculations and write the results in order to a vector.
I'm using a std::async
. The program works perfectly with a short pause (ref. the commented line). Without this pause, the program crashes.
The Code ( in an online IDE to modify & test the MCVE :
class AsyncDispatcher {
public:
/* Data is a custom class with data that contains a ID.
* The object contains no
* links or pointers.*/
vector<Data> calcResult(vector<Params> params) {
vector<Data> result;
vector<std::future<NumberedData>> futures;
threadID = 0;
for (auto param : params) {
futures.push_back(((std::async(std::launch::async, [&]() {
this_thread::sleep_for(chrono::milliseconds(100)); // not workable without this command
//^^^^^^^^^^^^^^^^^^^^^^^^^
return NumberedData(filler.createData(param, threadID), threadID);
}))));
threadID++;
}
for (auto& f : futures) {
result.push_back(f.get().data);
}
return result;
}
AsyncDispatcher() : threadID(0) {}
private:
int threadID;
Filler filler;//fills an Data with numbers
};