我知道很多人問這個問題,但我不是「很多人」,我需要一個不同的,更好的解釋來理解。線程上的「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)使您的生活更輕鬆。 –