c 11 – 是否有相同的packaged_task :: set_exception?

我的假设是packaged_task在下面有一个承诺.如果我的任务抛出异常,我该如何将其路由到相关的未来?只有一个承诺我可以调用set_exception
– 我如何为packaged_task做同样的事情?

解决方法

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

这意味着在与打包任务关联的函数内部抛出异常就足以使该异常被任务的未来捕获(并在未来对象上调用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();
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...