在 C++ 中,thread 之 detach()  可以将正在运行的执行线程与管理它的 thread 对象分离,使该线程作为“守护线程”在后台独立运行。一旦分离,原 thread  对象将不再控制实际的执行线程,你也无法再使用它来等待线程完成(即调用 join() 方法)。即,在线程完成启动后,直接释放线程句柄,不再等待线程完成,让线程在后台独立运行。

例如:

#include <atomic>

#include <thread>

#include <chrono>

using namespace std::chrono;

void tick(int n)

{

    for (int i = 0; i != n; ++i) {

        this_thread::sleep_for(seconds{ 1 }); // §42.2.6

        cout<<"Alive!"<<endl;

    }

}

int _tmain(int argc, _TCHAR* argv[])

{

    thread timer{ tick,10 };

    timer.detach();  // detach() 会释放线程句柄,不阻塞

    system("pause");

    return 0;

}

更多推荐