Let's say I have a method that calls an unstable third-party service, so I add a timeout for this call say 10 seconds. Here is what I tried:
int process()
{
std::promise<int> promise;
std::future<int> future = promise.get_future();
std::thread([&]
{
try
{
int result = call_third_party_service();
promise.set_value(result);
}
catch (std::exception&) //call_thrid_party_service can throw exceptions
{
promise.set_exception(std::current_exception());
}
}).detach();
auto status = future.wait_for(std::chrono::seconds(10));
if (status == std::future_status::timeout)
{
promise.set_exception(time_out_exception);
}
return future.get();
}
int main()
{
try
{
int result = process();
}
catch(const std::exception& e)
{
//print
}
//blocks the thread to see what happens
std::this_thread::sleep_for(std::chrono::minutes(1));
return 0;
}
When call_third_party_service
is not responding (assume it throws an exception saying timeout after 30 seconds), status == std::future_status::timeout
hits after 10 seconds' waiting, then promise.set_exception
works, and everything looks good. However when call_third_party_service
throws the exception, promise.set_exception
again, hence the Segmentation fault. What's the correct way to implement this pattern?