C++ Thread 库 - Function detach
描述
它在线程执行完成时返回。
声明
以下是 std::thread::detach 函数的声明。
void join();
C++11
void join();
参数
none
返回值
none
异常
No-throw guarantee − 从不抛出异常。
数据竞争
对象被访问。
示例
在下面的 std::thread::detach 示例中。
#include <iostream>
#include <chrono>
#include <thread>
void independentThread() {
std::cout << "Starting thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Exiting previous thread.\n";
}
void threadCaller() {
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
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));
}
输出应该是这样的 −
Starting thread caller. Starting thread. Exiting thread caller. Exiting previous thread.

