【问题标题】:C++11 thread detach not workingC ++ 11线程分离不起作用
【发布时间】:2017-09-04 10:42:24
【问题描述】:

我知道当产生一个新线程时,它必须被加入或分离,否则应调用终止,如果我加入它们,我有下面的代码可以正常工作,但如果我调用分离会崩溃,我不是能够理解幕后发生的事情。

#include "iostream"
#include "thread"
#include "vector"
#include "algorithm"
#include "iterator"
#include "string"
#include "memory"
using namespace std;

void func() {
    cout << " func ";
}

int main(int argc , char** argv)
{
    std::vector< std::thread> m_vec;
    for(int i = 0; i < 100 ; i++){
        m_vec.push_back( std::thread(func));
        m_vec[i].detach();
    }
    return 0;
}

【问题讨论】:

    标签: multithreading c++11


    【解决方案1】:

    仅仅分离一个线程并不能让它比主线程更长寿。一旦主线程退出,那就是球赛;堆被销毁,cout 之类的东西被清理干净。如果在整个进程终止之前执行任何操作,任何剩余的线程都有明显的崩溃机会。

    如果您detach 一个线程,请准备好提供您自己的机制来确保它不会超过主线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 2013-08-28
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多