[英]How to end a thread safely
在 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() 返回任何值。
那会发生什么?
您尝试销毁可连接的thread
对象,这会导致程序终止。
我这样好吗?
你不应该那样做。 无论是通话my_thread.join()
等待线程和清理其资源,或my_thread.detach()
使其清理线程退出时自动。
使用完线程后,您必须调用my_thread.join()
。 调用join()
告诉操作系统您完成了线程的使用,程序可以安全地终止,有效地将您的线程与主线程“加入”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.