【发布时间】:2020-08-14 16:32:40
【问题描述】:
我想运行一个超时的函数。如果达到超时,我想在超时发生之前访问线程生成的部分结果。
例如,我想在 c++17 中做类似的事情:
std::vector<int> my_result;
auto future = std::async(std::launch::async, [&my_result]() {
for (int i = 0; i < 100000; i++)
my_result.push_back(i);
});
auto status = future.wait_for(std::chrono::milliseconds(1));
if (status == std::future_status::timeout) {
std::cout << "Partial result:" << std::endl;
for (auto i : my_result)
std::cout << i << std::endl;
}
做这样的事情安全吗?如果在调用push_back() 期间发生超时,是否保证向量不会处于不一致状态?
如果没有,有没有更好的方法来做到这一点?
【问题讨论】:
标签: c++ multithreading future