C++ 多线程的错误和如何避免(2)
试图 join 一个已经 detach 的线程
如果你已经在某个地方分离了线程,那你不可以在主线程再次 join,这是一个明显的错误
比如:
#include#include using namespace std; void LaunchRocket() { cout << "Launching Rocket" << endl; } int main() { thread t1(LaunchRocket); t1.detach(); //..... 100 lines of code t1.join(); // CRASH !!! return 0; }
结果:(在 debug 模式下运行)
如何避免?
可以判断 joinable 的状态,比如
int main()
{
thread t1(LaunchRocket);
t1.detach();
//..... 100 lines of code
if (t1.joinable())
{
t1.join();
}
return 0;
}
什么是 joinable,可以参考:
小结:
在程序编译时不会报错,相反,在运行时会导致程序崩溃
不管是先 join 再 detach,还是重复 join 或者 detach,都会导致程序崩溃
参考:
- Top 20 C++ multithreading mistakes and how to avoid them