在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() 返回任何值。
最佳答案
What happens then?
您试图销毁可连接的thread
对象,这会导致程序终止。
I am ok like this?
你不应该那样做。要么调用 my_thread.join()
等待线程并清理其资源,要么调用 my_thread.detach()
使其在线程退出时自动清理。
关于c++ - 如何安全地结束一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302577/