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