如何安全地结束一个线程

时间:2015-02-03 15:26:25

标签: c++ multithreading

在C ++中,我可以创建一个如下的线程

#include <thread>

using namespace std;

void f()
{
    // Do something
    cout<<"Finished! I am going to return!"<<endl;
}

int main()
{
    thread my_thread(&f);

    // Do other things that, say, take a LOOOONG time to be executed, much longer than the execution time of the thread
}

线程my_thread启动,运行我的函数f。主线程继续执行main()函数,当它仍在执行时,另一个线程到达f()的末尾并返回。那么会发生什么?我很喜欢这个?线程刚刚关闭,我不必再打电话了吗?或者线程是否永远挂在那里,我需要调用一些清理函数?

请注意,我不需要进行任何同步,也不需要从f()返回任何值。

2 个答案:

答案 0 :(得分:4)

  

那会怎么样?

您尝试销毁可连接的thread对象,这会导致程序终止。

  

我很喜欢这个?

你不应该这样做。调用my_thread.join()等待线程并清理其资源,或my_thread.detach()使线程退出时自动清理。

答案 1 :(得分:2)

完成线程使用后,您必须致电my_thread.join()。调用join()告诉操作系统你完成使用线程和程序可以安全地终止,有效地将你的线程“加入”主线程。