是否有相同的packaged_task :: set_exception?

时间:2013-05-02 17:59:14

标签: c++11 exception-handling future promise packaged-task

我的假设是packaged_task下面有promise。如果我的任务抛出异常,我该如何将其路由到关联的future?只需promise我就可以致电set_exception - 我如何为packaged_task做同样的事情?

1 个答案:

答案 0 :(得分:10)

std::packaged_task有一个关联的std::future对象,它将保存异常(或任务的结果)。您可以通过调用std::packaged_task的{​​{3}}成员函数来检索该未来。

这意味着在throw与打包任务关联的函数内部发生异常就足以使该异常被任务的未来捕获(并在调用get()时重新抛出该异常关于未来的对象)。

例如:

#include <thread>
#include <future>
#include <iostream>

int main()
{
    std::packaged_task<void()> pt([] () { 
        std::cout << "Hello, "; 
        throw 42; // <== Just throw an exception...
    });

    // Retrieve the associated future...
    auto f = pt.get_future();

    // Start the task (here, in a separate thread)
    std::thread t(std::move(pt));

    try
    {
        // This will throw the exception originally thrown inside the
        // packaged task's function...
        f.get();
    }
    catch (int e)
    {
        // ...and here we have that exception
        std::cout << e;
    }

    t.join();
}
相关问题