c++ - 如何安全地结束一个线程

标签 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() 返回任何值。

最佳答案

What happens then?

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

I am ok like this?

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

关于c++ - 如何安全地结束一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302577/

相关文章:

java - display.async 和平滑过渡

linux - 当从另一个线程发出信号时,如何在阻塞套接字上从 "disengage"返回 `accept`?

c++ - decltype 不解析嵌套 vector 。如何使用嵌套 vector 的模板?

c++ - 如何配置 Emacs 以突出显示违反详细代码样式的 C++?

c++ - 如何确定无格式输入函数读取的字符数?

c++ - 从没有对象的 Objective C 调用特定的 C++ 方法

c++ - 如何将 char 值转换为特定的 int 值

java - 我如何知道守护进程是否从不同的线程停止

c# - NUnit 辅助线程异常

java - 2 个线程和 2 个 JTextArea