gpt4 book ai didi

c++ - std::promise set_exception 两次导致段错误

转载 作者:太空狗 更新时间:2023-10-29 20:50:13 26 4
gpt4 key购买 nike

假设我有一个调用不稳定的第三方服务的方法,所以我为这个调用添加了一个超时时间,比如 10 秒。这是我尝试过的:

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;
}

call_third_party_service 没有响应时(假设它在 30 秒后抛出异常提示超时),status == std::future_status::timeout 在 10 秒后命中等待,然后 promise.set_exception 工作,一切看起来都很好。但是,当 call_third_party_service 抛出异常时,promise.set_exception 再次抛出,因此出现 Segmentation 错误。实现此模式的正确方法是什么?

最佳答案

根据Frax的建议,您应该将promise移到lambda中,并在future超时时直接抛出异常:

int process() {
std::promise<int> promise;
std::future<int> future = promise.get_future();

// move ownership of the promise into thread
std::thread([prom = std::move(promise)]() mutable {
try {
int result = call_third_party_service();
prom.set_value(result);
} catch (std::exception&) // call_thrid_party_service can throw exceptions
{
prom.set_exception(std::current_exception());
}
}).detach();

auto status = future.wait_for(std::chrono::seconds(10));
if (status == std::future_status::timeout) {
// This exception is not part of an asynchronous computation and
// should be thrown immediately
throw time_out_exception("timed out");
}

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;
}

关于c++ - std::promise set_exception 两次导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55915552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com