c ++ 0x中线程之间的异常传播

时间:2011-03-29 10:08:44

标签: multithreading exception-handling c++11

我正在使用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,但是在它之外它是?! 这有什么不对?

1 个答案:

答案 0 :(得分:2)

我自己想通了。 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;
}