[英]How to terminate a thread safely? (with the usage of pointer) c++
我目前正在 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;
}
output 是:
Hello WorldHello World12
Hello World12
没有报告错误。 这让我非常困惑。
所以我的问题是:
非常感谢!
使用动态分配创建对象时,您必须使用operator delete
释放 memory 以便它调用适当的析构函数。
在第一个示例中,创建了两个std::thread
对象。 在main
function 的末尾,调用了析构函数std::thread::~thread
。 由于线程没有加入,析构函数会报错。
另一方面,在第二个示例中,您调用了operator new
,以便创建具有动态分配的对象。 但是,您没有调用operator delete
,因此不会调用析构函数。 也就是说,程序没有检查线程是否被加入。
因此,正确终止线程的唯一方法是调用std::thread::join
。 如果要使用指针,则必须执行以下操作:
std::thread *th = new std::thread(foo);
...
th->join();
delete th;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.