问题描述
我尝试并行化计算并将结果写入向量。
我正在使用std::async
。该程序可以在短暂停顿(参考注释行)的情况下完美运行。没有此暂停,程序将崩溃。
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
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)