gpt4 book ai didi

c++ - 从具有本地 std::thread 对象但未连接的函数中退出

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:46 28 4
gpt4 key购买 nike

我有以下简单的功能,仅供演示:

void thread_func(int i) {
return i;
}

我还有另一个函数在新线程中调用它并且不等待它返回:

void my_nice_function() {
std::thread t(thread_func, 15);
}

由于 tmy_nice_function() 中的局部变量,我担心当 my_nice_function() 退出时,t 会在运行时销毁。

有理由担心吗?即使从 my_nice_function() 返回后,如何让线程 t 在后台运行?

最佳答案

您的担心是有道理的。适合读书reference documentation for std::thread告诉我们在销毁时:

If *this has an associated thread (joinable() == true), std::terminate() is called.

因此,在不分离或加入的情况下销毁 t 将结束您的程序。

因此,您有两种选择,具体取决于您希望发生什么。如果您希望函数等待线程完成,请在返回前调用 t.join()。如果您希望线程在函数返回后继续运行,请调用 t.detach()

关于c++ - 从具有本地 std::thread 对象但未连接的函数中退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015846/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com