简体   繁体   English

如何安全地结束线程

[英]How to end a thread safely

In C++ I can create a thread as follows在 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
}

The thread my_thread starts, runs my function f.线程 my_thread 启动,运行我的函数 f。 The main thread keeps executing the main() function, and while it is still executing the other thread reaches the end of f() and returns.主线程继续执行 main() 函数,在它仍在执行的同时另一个线程到达 f() 的末尾并返回。 What happens then?那会发生什么? I am ok like this?我这样好吗? The thread is just closed and I don't have to call anything else?线程刚刚关闭,我不必调用其他任何东西? Or does the thread stay there hanging forever and I need to call some cleanup function?或者线程是否永远挂在那里,我需要调用一些清理函数?

Please note that I don't need to do any synchronization and no value needs to be returned from f().请注意,我不需要进行任何同步,也不需要从 f() 返回任何值。

What happens then?那会发生什么?

You attempt to destroy a joinable thread object, which causes the program to terminate.您尝试销毁可连接的thread对象,这会导致程序终止。

I am ok like this?我这样好吗?

You shouldn't do that.你不应该那样做。 Either call my_thread.join() to wait for the thread and clean up its resources, or my_thread.detach() to make it clean up automatically when the thread exits.无论是通话my_thread.join()等待线程和清理其资源,或my_thread.detach()使其清理线程退出时自动。

You must call my_thread.join() once you're finished using the thread.使用完线程后,您必须调用my_thread.join() Calling join() tells the operating system that your finished using the thread and the program can safely terminate, effectively "joining" your thread with the main thread.调用join()告诉操作系统您完成了线程的使用,程序可以安全地终止,有效地将您的线程与主线程“加入”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM