标签:return wrap code int main raii app 多线程 std
thread对象必须调用join或者detach,否则程序会终止
例如:
void func()
{
std::cout << "hello, " << std::this_thread::get_id() << std::endl;
}
int main()
{
std::thread t(func);
return 0;
}
也可能在join/detach之前抛出异常导致没有正常调用join/detach
void func()
{
......
}
int main()
{
std::thread t(func);
......
where (......)
{
......
// 这里抛出异常
}
......
t.join();
return 0;
}
上面这段代码在where块里抛出异常导致join没有被调用
第一种解决方法是加上try-catch块
......
try {
where () { ...... }
} catch (......) {
if (t.joinable())
t.join();
throw;
}
......
t.join();
......
第二种方法使用RAII,将thread对象放到自定义类型classT中,在classT的析构方法里尝试调用join/detach
class Wrapper
{
public:
......
~Wrapper() { if (m_t.joinable()) m_t.join(); }
......
private:
std::thread m_t;
}
标签:return wrap code int main raii app 多线程 std
原文地址:https://www.cnblogs.com/ChenLambda/p/11724976.html