vso*_*tco 6 c++ asynchronous future exception c++11
我无法理解如何std::async存储任何异常,而不仅仅是从std::exception. 我玩弄下面的代码
#include <iostream>
#include <future>
#include <chrono>
void f()
{
std::cout << "\t\tIn f() we throw an exception" << std::endl;
throw 1; // throw an int
}
int main()
{
std::future<void> fut = std::async(std::launch::async, f);
std::cout << "Main thread sleeping 1s..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep one second
std::cout << "Main thread waking up" << std::endl;
try
{
fut.get();
}
catch(...)
{
std::cout << "We caught an exception!" << std::endl;
throw; // rethrow
}
}
Run Code Online (Sandbox Code Playgroud)
我f()异步启动,然后抛出一个int内部f. 神奇的是, thisint被std::async.返回的未来捕获并存储。我知道 中catch(...)的异常是可能的std::async,但是后者如何在不知道异常类型的情况下存储它?异常不是从某个基类派生的(在这种情况下,人们可能可以通过 some 来“克隆”它Base::clone),但可以是任何异常。我们能否以某种方式神奇地“推导出”异常类型?
总而言之,我的问题是:
我们如何在不知道异常类型的情况下将任意异常存储在对象中,然后在稍后的某个时间重新抛出它?
std::async可以在std::thread和之上实现std::packaged_task。
std::packaged_task可以(部分)在std::exception_ptr相关函数之上实现(线程退出就绪函数除外)。
std::exception_ptr 和相关函数不能用 C++ 编写。
| 归档时间: |
|
| 查看次数: |
1778 次 |
| 最近记录: |