【C++编程】 std::detach()用法
1 #include <chrono> 2 #include <thread> 3 4 void independentThread() 5 { 6 std::cout << "Starting concurrent thread.\n"; 7 std::this_thread::sleep_for(std::chrono::seconds(2)); 8 std::cout << "Exiting concurrent thread.\n"; 9 } 10 11 void threadCaller() 12 { 13 std::cout << "Starting thread caller.\n"; 14 std::thread t(independentThread); 15 t.detach(); 16 std::this_thread::sleep_for(std::chrono::seconds(1)); 17 std::cout << "Exiting thread caller.\n"; 18 } 19 20 int main() 21 { 22 threadCaller(); 23 std::this_thread::sleep_for(std::chrono::seconds(5)); 24 }
输出:
1 #include <iostream> 2 #include <chrono> 3 #include <thread> 4 using namespace std; 5 6 void independentThread() 7 { 8 std::cout << "Starting concurrent thread.\n"; 9 std::this_thread::sleep_for(std::chrono::seconds(10)); 10 std::cout << "Exiting concurrent thread.\n"; 11 } 12 13 void threadCaller() 14 { 15 std::cout << "Starting thread caller.\n"; 16 std::thread t(independentThread); 17 t.detach(); 18 std::this_thread::sleep_for(std::chrono::seconds(1)); 19 std::cout << "Exiting thread caller.\n"; 20 } 21 22 int main() 23 { 24 threadCaller(); 25 std::this_thread::sleep_for(std::chrono::seconds(1)); 26 }
输出: