c++ - 标准线程分离

标签 c++ std

有这个简单的例子:

#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void new_thread(int n) {
    std::this_thread::sleep_for(std::chrono::seconds(n));
    std::cout << "New thread - exiting!\n";
}

int main() {    
    std::thread (new_thread, 5).detach();
    std::cout << "Main thread - exiting!\n";

    return 0;
}

是否有可能new_thread不被主线程自动终止并完成它的工作 - 5秒后输出New thread - exiting!

我的意思不是主线程等待子线程时加入的情况,而是主线程分离生成的线程并终止,让新线程继续工作?

最佳答案

调用detach在线程上意味着你不再关心线程做了什么。如果该线程在程序结束之前(当 main 返回时)没有完成执行,那么您将看不到它的效果。

但是,如果调用线程的时间足够长以使分离线程完成,那么您将看到输出。 Demo .

关于c++ - 标准线程分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63756317/

相关文章:

C++ Do - While 循环直到字符串满足特定条件

c++ - C++中的嵌套继承

c++ - 负数在 C/C++ 中返回 false 吗?

c++ - C stdlib/stdio 的阴影函数

c++ - 第一次分配后如何更改const std::shared_ptr?

c++ - 使用 std::vector 的链接错误

c++ - .cpp 文件被转换为 .cc 文件,当项目被导入到 eclipse 时

c++ - 如何在 x86 和 x64 中对函数进行 thunk? (类似于 C++ 中的 std::bind,但是是动态的)

c++ - 在共享库中使用重载的new/delete和STL

c++ - C++ std::container( vector )如何存储其内部结构(元素地址、按索引访问)?