【问题标题】:terminate called without an active exception thread c++在没有活动异常线程c ++的情况下调用终止
【发布时间】:2015-07-31 09:17:30
【问题描述】:

晚上好,我发现这个错误已经好几个小时了,我找到了很多解决方案,但它们都不起作用。

C_t 是向量的向量,它的大小是 100。如果循环一直到 8,它可以工作,但是当我增加它时,就会抛出错误。

f 是保存 C_t 求值的向量。

func 是函数的种类。

int nThreads = thread::hardware_concurrency();  // # threads
vector<thread> ths(nThreads);   // threads vector
cout << ths.size() << endl;

//Launching threads
int idx = 0;
for ( int i = 0 ; i < 10 ; i++ ){

    ths[idx] = thread( parallel_eval, ref(f[i]) ,  ref(C_t[i]) , func);

    // idx = idx != nThreads ? idx++:0;
    if(idx != nThreads){
        idx++;
    }
    else{
        idx = 0;
    }
    // std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}

//Joining threads
for ( int i = 0; i < nThreads; i++ ){
    ths[i].join();
}

【问题讨论】:

    标签: c++ terminate


    【解决方案1】:

    错误很可能是由ths 引起的。说明:

    您节省硬件并发级别:

    int nThreads = thread::hardware_concurrency();
    

    您为线程对象创建容器:

    vector<thread> ths(nThreads);
    

    然后,您创建并保存最多N 个线程:

    ths[idx] = thread( parallel_eval, ref(f[i]) ,  ref(C_t[i]) , func);
    

    这是你的问题:

    if(idx != nThreads)
    {
        idx++;
    }
    else
    {
        idx = 0;
    }
    

    这个条件本质上意味着:“在当前索引下保存线程。如果我们到达nThreads,将索引设置为0并继续保存在那里

    因此,基本上,如果您将N(循环的控制值和正在创建的线程数)的限制设置为大于nThreads 的值,您覆盖您的线程对象(通过移动赋值运算符)。为什么这是个问题?因为documentation 说:

    std::thread::operator=

    使用移动语义将 other 的状态分配给 *this

    如果*this 仍有关联的运行线程(即joinable() == true),则调用std::terminate()

    由于您覆盖的线程对象代表活动线程,因此满足调用std::terminate() 的条件。

    此外,我们现在可以轻松判断为什么每个 n &lt;= 8 都有效:您的 hardware_concurrency() 很可能是 8

    我会去:

    vector<thread> ths; //No need for any size restrictions. `vector<>` is a dynamic container, it will grow as necessary.
    
    for ( int i = 0 ; i < 10 ; i++ )
    {
        ths.emplace_back(parallel_eval, ref(f[i]) ,  ref(C_t[i]) , func);
    }
    
    for (auto t = ths.begin(); t != ths.end(); ++t)
    {
        t->join();
    }
    

    【讨论】:

    • 比我的答案要好得多。致敬!
    • 错误的成员函数 - 你想要移动赋值运算符,而不是析构函数。不过,“如果可加入则终止”部分是相同的。
    • 谢谢你,马特乌兹。它有效,但我没有加速或加速。我会检查它。再次感谢您。
    【解决方案2】:

    愿意在 nThreads == 8 上投入资金。

    如果是这种情况,vector&lt;thread&gt; ths(nThreads); 将在其内部数组中创建 8 个元素,ths[idx] = thread( parallel_eval, ref(f[i]) , ref(C_t[i]) , func); 将在第 9 个线程上运行。

    解决方案:要么将 ths 的初始大小锁定为要创建的线程数,要么不费心分配 ths 和 push_backemplace_back 线程的初始大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-09
      • 2021-07-02
      • 2016-10-07
      • 1970-01-01
      • 2020-03-06
      • 2021-10-10
      • 2014-10-14
      • 1970-01-01
      相关资源
      最近更新 更多