c++0x 中线程之间的异常传播
我正在使用 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,但在外面却是?! 这是怎么回事?
I'am using gcc 4.5 and want to transfer an exception to a different thread:
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;
}
The output I get:
caught
outside NULL
Seems e
is not NULL inside the thread, but then outside it is?!
What's wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己想出来了。 std::thread 首先创建 struct Callable 的副本...
以下内容按预期工作:
I figured it out myself. std::thread makes a copy of
struct Callable
first...The following works as expected: