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;
}
}
を考えます。 g ++ 6.2.0を使用しています。しかし、MS VS2015バージョン14.0.25431.01 Update 3を使用すると、応答はValid: 1
になります。将来の状態は、例外がメインスレッドに伝播された後、無効にされません。これはバグですか、私はここで未定義の振る舞いをしていますか?
回避策はありますか?私はwait_forステートメントを削除すると、期待どおりに動作しますが、私のプロダクションコードでは、サンプルソースに似たプログラムフローが必要です。 – IcePic
@IcePicは代わりに 'concurrency :: task'を使うかもしれません。 VC++の下では、 'std :: async'はとにかくタスクを囲む薄いラッパーです。 –