多线程中的detach

為{幸葍}努か 提交于 2019-11-27 19:19:51

从 thread 对象分离执行的线程,允许执行独立地持续。一旦线程退出,则释放所有分配的资源。(就是两个线程彼此相互独立)

调用 detach 后, *this 不再占有任何线程。

#include <iostream>
#include <chrono>
#include <thread>

void independentThread()
{
    std::cout << "Starting concurrent thread.\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.\n";
}

void threadCaller()
{
    std::cout << "Starting thread caller.\n";
    std::thread t(independentThread);
     t.detach(); //分离,主线程和子线程彼此独立进行:不会出现join()的那种等待子线程结束再执行主线程;也不会出现什么都不操作,主线程结束后杀掉子线程,报abort的错误.
    //可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached,不然会报abort错误.
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.\n";
}

int main()
{
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(5));
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!