如何在多线程 C++ 中传递多维数组

how to pass multidimensional array in multithreading c++

本文关键字:数组 多线程 C++      更新时间:2023-10-16

我试图创建多线程来处理 2 个多维数组:

vector<thread> tt;  
for(int i=0;i<4;i++) tt.push_back(thread(th,arr1,arr2));

使用线程函数:

void th(int arr1[3][100][100], int arr2[100][100]) {
...
}

我也试图通过引用传递,但也没有让它工作:

void th(int (&arr1)[3][100][100], int (&arr2)[100][100]) {
    ...
    }

他们两个都给了我一个"no type named 'type' in 'class std::result_of void(* (int **[])..."错误。有人可以告诉我如何在多线程中正确传递多维数组吗?

您的原始函数调用对我来说闻起来很奇怪,但以下调用仍然可以编译并使用命令进行g++-4.6.3运行良好

g++ -lpthread -std=c++0x -g multiArray.cc -o multiArray && ./multiArray

那么multiArray.cc

#include <iostream>
#include <thread>
#include <vector>
void th(int ar1[3][100][100], int ar2[100][100])
{
    std::cout << "This works so well!n";
}
int main()
{
    int ar1[3][100][100];
    int ar2[100][100];
    std::vector<std::thread> threads;
    for(int ii = 0; ii<4; ++ii)
    {
        threads.emplace_back(th, ar1,ar2);
    }

    for(auto & t : threads)
    {
        if(t.joinable())
        {
            t.join();
        }
    }
}

让我澄清一下,这段代码是可疑的;例如,如果你改变数组大小(不改变你的数组尺寸),这段代码编译没有问题。