我知道很多人问这个问题,但我不是“很多人”,我需要一个不同的,更好的解释来理解。线程上的“detach()”是什么? CPP
成员函数“detach()”到底是什么? 我试着运行一个代码示例:
#include <iostream>
#include <chrono>
#include <thread>
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(200));
std::cout << "Exiting concurrent 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));
}
并在5秒内的所有程序关闭。 我认为程序会在“main”关闭后的另一个195秒后打开,因为“detach”的所有概念都是与main无关的,所以以独立的方式,它应该仍然运行直到所有分离的游戏都终止... 我阅读文档并来到这里。 更好的解释 - 请! :)
通过使用['std :: async'](http://en.cppreference.com/w/cpp/thread/async)使您的生活更轻松。 –