從 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)); }