thread :: detach()在C ++ 11中如何工作? [英] How does thread::detach() work in C++11?

查看:139
本文介绍了thread :: detach()在C ++ 11中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码,但无法理解为什么它不能像main()线程一样打印出threadFunc()中的所有no(即0到-99)。

I wrote the following code and am unable to understand why doesn't it prints out all the no's(i.e. 0 to -99) in threadFunc() as it does with main() thread.

#include<iostream>
#include<thread>
#include<string>
#include<mutex>
#include<chrono>

using namespace std;

mutex mu;

void threadFunc(){
    for(int i=0;i>-100;i--){
    std::this_thread::sleep_for(std::chrono::milliseconds(30)); /*delay for 30ms*/
    mu.lock();
    cout<<"Thread:  "<<i<<endl;
    mu.unlock();
    }
}

main(){

    thread t1(threadFunc);   


    for(int i=0;i<100;i++){
    mu.lock();
    cout<<"Main:  "<<i<<endl;
    mu.unlock();    
    }


    cout<<"End of Main"<<endl;  

    t1.detach();   
}

程序的输出为:

Main: 0  
Main: 1  
.  
.  
.  
Main: 99  
End of Main.  
Thread: -1 


推荐答案

进程在以下时间终止 main()退出,所有线程被杀死。您会在程序中观察到这种行为。

Process terminates when main() exits, and all threads are killed. You observe this behavior in your program.

Detach基本上说,从现在开始,您不能加入线。但是,如果您不能加入,则无法让您的 main()等到它完成(除非您使用其他同步原语)-因此它很高兴退出。

Detach basically says that from now on, you can't join this thread. But if you can't join it, you can't make your main() to wait until it completes (unless you use other synchronization primitives) - and thus it is happily exiting.

这就是为什么我强烈劝阻每个人不要使用分离线程的原因,它们很难正确执行。

This is why I strongly discourage everybody from using detached threads, they are very hard to do properly.

这篇关于thread :: detach()在C ++ 11中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆