stdthread(3)detach
生活随笔
收集整理的這篇文章主要介紹了
stdthread(3)detach
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 脫離主線程的綁定,主線程掛了,子線程不報錯,子線程執行完自動退出。
void pause_thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));std::cout << "pause of " << n << " seconds ended\n"; }int test() {std::cout << "Spawning and detaching 3 threads...\n";std::thread (pause_thread,1).detach();std::thread (pause_thread,2).detach();std::thread (pause_thread,3).detach();std::cout << "Done spawning threads.\n";std::cout << "(the main thread will now pause for 5 seconds)\n";// give the detached threads time to finish (but not guaranteed!):pause_thread(5);return 0; }輸出:
Spawning and detaching 3 threads... Done spawning threads. (the main thread will now pause for 5 seconds) pause of 1 seconds ended pause of 2 seconds ended pause of 3 seconds ended pause of 5 seconds ended1.1 當對象析構時線程會繼續在后臺執行,但是當主程序退出時并不能保證線程能執行完。
void thread1() {for(int i=0;i<20;++i)cout << "thread1... " << i << endl;}void thread2() {for (int i = 0; i<20; ++i)cout << "thread2... " << i << endl;}int test() {thread th1(thread1); //實例化一個線程對象th1,該線程開始執行thread th2(thread2);th1.detach();th2.detach();cout << "main..." << endl;return 0;}輸出結果是不確定的
main...thread1... detach test 或者 main...thread1... detach test 0 0總結
以上是生活随笔為你收集整理的stdthread(3)detach的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: stdthread(2)创建
- 下一篇: STL源代码分析(ch2 内存分配)de