【发布时间】:2016-03-23 02:16:47
【问题描述】:
class ThreadGuard {
public:
ThreadGuard(std::thread &t_): t(t_) {}
~ThreadGuard()
{
if(t.joinable())
t.join();
}
private:
std::thread &t;
};
void func()
{
std::thread my_thread(f);
ThreadGuard thread_guard(my_thread);
}
我尝试使用 ThreadGuard 对象来保证函数在线程正常终止之前不会退出。但是如果在创建 thread_guard 对象之前发生异常怎么办。
【问题讨论】:
-
应该没问题。如果抛出异常,意味着线程构造失败,那么线程不应该运行,函数应该退出。对吗?
-
−1
if(t.joinable)不是真正的代码。 -
对不起,我弄错了。应该是
if(t.joinable())。 -
线程构造成功,thread_guard构造失败。线程已经运行。
标签: c++ multithreading exception-handling