【发布时间】:2019-10-19 06:16:17
【问题描述】:
我目前正在学习 c++11 中的多线程,我对安全终止线程的方式感到困惑。
在 c++ 中,我知道如何创建线程并使用 thread.join() 来安全地确保 main() 在退出之前等待所有线程完成。
但是,我发现一些通过指针实现的多线程代码即使不使用 thread.join() 也能够运行。
class Greating
{
public:
Greating(const int& _i):i_(_i){}
~Greating(){}
int i_;
void say()
{
std::cout << "Hello World" << i_ << std::endl;
}
};
int main(){
Greating greating1(1);
Greating greating2(2);
std::thread t1(&Greating::say, greating1);
std::thread t2(&Greating::say, greating2);
return 0;
}
上面显示的代码绝对会报错"terminate called without an active exception Aborted (core dumped)”,因为我没有使用 t1.join() 和 t2.join()。
但是我在一些代码中发现当他们使用指针来管理线程时,这并没有成为问题,如下图。
class Greating
{
public:
Greating(const int& _i):i_(_i){}
~Greating(){}
int i_;
void say()
{
std::cout << "Hello World" << i_ << std::endl;
}
};
int main(){
Greating greating1(1);
Greating greating2(2);
std::thread* tt1 = new std::thread(&Greating::say, greating1);
std::thread* tt2 = new std::thread(&Greating::say, greating2);
return 0;
}
输出是:
Hello WorldHello World12
Hello World12
没有报告错误。这让我很困惑。
所以我的问题是:
- 为什么当我们使用指针管理线程时,不能使用函数thread.join()?
- 如何正确终止线程? (可能要等待可调用函数完成?)
非常感谢!
【问题讨论】:
-
对指针的大切换有以下效果:泄漏线程对象。否则,线程对象将在没有加入或分离的情况下被销毁。因此,只有第一个案例报告该错误才有意义。
标签: c++ multithreading c++11