如何解决在循环中运行std :: async如何获得一致的结果?
我尝试并行化计算并将结果写入向量。
我正在使用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 举报,一经查实,本站将立刻删除。