【问题标题】:Exception propagation between threads in c++0xc++0x中线程之间的异常传播
【发布时间】:2011-03-29 10:08:43
【问题描述】:

我正在使用 gcc 4.5 并希望将异常转移到不同的线程: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2179.html

#include <stdexcept>
#include <iostream>
#include <thread>

struct Callable
{
    void operator()()
    {
        try
        {
            throw std::runtime_error("Bad things happened");
        }
        catch (...)
        {
            std::cout << "caught" << std::endl;
            e = std::current_exception();

            if (e == NULL)
            {
                std::cout << "inside NULL" << std::endl;
            }
        }
    }

    std::exception_ptr e;
};

int main()
{
    Callable c;

    std::thread t(c);
    t.join();

    if (c.e == NULL)
    {
        std::cout << "outside NULL" << std::endl;
    }
    else
    {
        std::rethrow_exception(c.e);
    }

    return 0;
}

我得到的输出:

caught
outside NULL

似乎e 在线程内部不是NULL,但在外部它是?! 这里有什么问题?

【问题讨论】:

    标签: multithreading exception-handling c++11


    【解决方案1】:

    我自己想通了。 std::thread 首先复制struct Callable...

    以下按预期工作:

    #include <stdexcept>
    #include <iostream>
    #include <thread>
    
    int main()
    {
        std::exception_ptr e;
    
        std::thread t([&e]()
        {
            try
            {
                throw std::runtime_error("Bad things happened");
            }
            catch (...)
            {
                std::cout << "caught" << std::endl;
                e = std::current_exception();
    
                if (e == NULL)
                {
                    std::cout << "inside NULL" << std::endl;
                }
            }
        });
    
        t.join();
    
        if (e == NULL)
        {
            std::cout << "outside NULL" << std::endl;
        }
        else
        {
            std::rethrow_exception(e);
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 2010-09-18
      • 1970-01-01
      • 2011-11-08
      • 2010-10-30
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      相关资源
      最近更新 更多