【问题标题】:C++ thread library exceptionC++ 线程库异常
【发布时间】:2020-02-03 13:06:39
【问题描述】:

我对 C++ 线程库有一些问题。我已经调整了旧代码以优化新问题,突然抛出未捕获的异常(在运行时)。一些线程成功加入,但总是至少有一个抛出异常。我在代码中唯一改变的是数据表示。它们之前保存在二维数组中,现在我使用的是一维向量。这是我收到的确切运行时错误:

libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: Invalid argument

下面我提供了最小的可重现示例,抛出与完​​整代码完全相同的异常。

这里是主要功能:

#include <iostream>
#include <thread>
#include <vector>

void reforming(const int, const std::vector<int>&, const std::vector<double>&, const std::vector<double>&);

int main() {
    int i, k;
    int spec_max = 10;
    int seg_max = 4;
    size_t pop_size = spec_max * seg_max;
    std::vector<int> seg(pop_size);
    std::vector<double> por(pop_size);
    std::vector<double> por_s(pop_size);

    for(i = 0; i < pop_size; i++){
        if(i % 2 == 0){
            seg[i] = 1;
            por[i] = 0.5;
            por_s[i] = 0.0015;
        } else {
            seg[i] = 0;
            por[i] = 0.7;
            por_s[i] = 0.002;
        }
    }

    std::vector<std::thread> Ref(spec_max);
    for(k = 0; k < spec_max; k++){
        Ref.emplace_back(reforming, k, seg, por, por_s);
    }

    for(auto &X : Ref){
        X.join();
    }
    return 0;
}

以及“改造”功能:

#include <iostream>
#include <vector>

void reforming(const int m, const std::vector<int>& cat_check, const std::vector<double>& por,
        const std::vector<double>& por_s){

        std::cout << m << " Hello from the thread\n";
}

我在 MacOS Catalina 上使用 CLion 软件,目前没有其他操作系统可用于测试代码。

【问题讨论】:

  • 只是一个侧面不是,在 C++ 中,变量以大写形式表示并不常见。
  • 我知道,只是原始代码有大量的变量。我开始使用大写字母来更快地识别它们

标签: c++ multithreading exception


【解决方案1】:

以下代码:

std::vector<std::thread> Ref(spec_max);
for(k = 0; k < spec_max; k++){
    Ref.emplace_back(reforming, k, seg, por, por_s);
}

创建2 * spec_max 线程,第一个spec_max 线程默认初始化。尝试加入默认初始化的线程会抛出 std::system_error

修复:

std::vector<std::thread> Ref;
Ref.reserve(spec_max);
for(k = 0; k < spec_max; k++){
    Ref.emplace_back(reforming, k, seg, por, por_s);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2010-11-10
    • 2011-05-27
    • 2014-09-10
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多