I am trying to parallelize calculations and writing the results in order to a vector. I'm using an std::async. The program works perfectly with a short pause (commented line). Without this pause, the program crashes.
Code:
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
};
Thanks for any advice. And I'm sorry.
Aucun commentaire:
Enregistrer un commentaire