在不同机器上执行时出现错误“std::system_error”

问题描述 投票:0回答:1

我尝试了一个在第 12 代 Intel(R) Core(TM) i7-1265U 上使用线程的 cpp 程序,在 Intel(R) Xeon(R) Silver 4216 CPU 上运行的容器上尝试相同的程序时没有出现任何错误@ 2.10GHz 我收到以下错误错误图像

#include <iostream>
#include <cstdlib>
#include <thread>
#include <chrono>
#include<vector>

using namespace std;
using namespace std::chrono;

void fillRandom(float *arr, int size) {
    for (int i = 0; i < size; ++i) {
        arr[i] = static_cast<float>(rand()) / RAND_MAX * 10.0;
}
}
void helper(float *c,float*a,float*b,int n,int o,int i,int j)
{
            int t=0,l;
            for (l = 0; l < o; l++) {
                t += a[i * o + l] * b[l * n + j];
            }
            c[i * n + j] = t;

}
void matmul(float *a, float *b, float *c, int m, int n, int o) {
    vector <thread> threads;
    int i, j, l, t;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {

            threads.emplace_back(&helper,c,a,b,n,o,i,j);
        }
    }
    for(auto& th : threads){
    th.join();
}
}

int main(int argc, char *argv[]) {

    srand(static_cast<unsigned int>(time(nullptr)));

    int m = 256;
    int n = m;
    int repetitions = 10;

    float *a = new float[m * n];
    float *b = new float[m * n];
    float *c = new float[m * n];

    fillRandom(a, m * n);
    fillRandom(b, m * n);


    for (int rep = 0; rep < repetitions; ++rep) {
        auto start = high_resolution_clock::now();
        matmul(a, b, c, m, n, m);
        auto stop = high_resolution_clock::now();
        auto duration = duration_cast<milliseconds>(stop - start);
        cout << "Time taken for " << rep<< "th repetition is " << duration.count() << " milliseconds" << endl;


    }

    delete[] a;
    delete[] b;
    delete[] c;

    return 0;
}

这是一个多线程矩阵乘法代码,我对此很陌生,一些帮助会很好,谢谢。

c++ multithreading runtime-error
1个回答
0
投票

std::thread 构造函数 可以抛出

std::system_error

异常可能表示错误条件 std::errc::resource_unavailable_try_again 或另一个特定于实现的错误条件。

您正在尝试创建 65536 个线程,因此您得到“资源暂时不可用”似乎是合理的。用 try-catch 块包围你的线程创建

try {
    threads.emplace_back(&helper,c,a,b,n,o,i,j);
}
catch (const std::exception& e) {
    std::cout << "Failed to create thread on iteration: " << i << ", " << j << "\n";
}

并查看您的机器上有多少“太多”。

© www.soinside.com 2019 - 2024. All rights reserved.