5
考慮下面的源代碼的std ::期貨和異常
#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <chrono>
int main() {
auto task = std::async(std::launch::async, [] {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
throw std::runtime_error("error");
});
try {
while (task.wait_for(std::chrono::seconds(0)) !=std::future_status::ready)
{
std::cout << "Not ready: " << std::endl;
}
task.get();
}
catch (const std::exception& e)
{
std::cout << "Valid: " << task.valid() << std::endl;
}
}
我預計,該計劃將與Valid: 0
響應。使用g ++ 6.2.0就是這種情況。但是,使用MS VS2015版本14.0.25431.01更新3的響應是Valid: 1
。在異常傳播到主線程之後,未來的狀態不會失效。這是一個錯誤還是我在這裏遇到未定義的行爲?
有沒有解決方法?當我刪除wait_for語句時,它按預期工作,但在我的生產代碼中,我需要類似於示例源的程序流。 – IcePic
@IcePic也許使用'concurrency :: task'。在VC++下,'std :: async'是一個簡單的包裝任務。 –