【问题标题】:how to pass multidimensional array in multithreading c++如何在多线程c ++中传递多维数组
【发布时间】:2015-03-01 00:41:47
【问题描述】:

我试图创建多线程来处理 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 **[])..." 错误。有人可以告诉我如何在多线程中正确传递多维数组吗?

【问题讨论】:

  • 去掉多线程,专注于让你的函数声明和调用正确。
  • tt.push_back(thread(th, std::ref(arr1), std::ref(arr2))); 和 std::ref 和 th 引用数组(所以 void th(int (&amp;arr1)[3][100][100], int (&amp;arr2)[100][100]))
  • ideone.com/RkR40P 看看使用 std::array 是多么容易。永远不要使用原始数组
  • @PiotrS。谢谢彼得。我确实尝试了 ref,但是,得到了同样的错误。
  • @ChuNan 请附上MCVE

标签: c++ multithreading c++11 multidimensional-array pass-by-reference


【解决方案1】:

你原来的函数调用对我来说闻起来很奇怪,但下面的调用仍然可以编译并运行得很好,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();
        }
    }
}

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

【讨论】:

  • 谢谢。我们也可以通过引用传递吗?
  • 我认为如果更改数组值会更快?
  • @NickThompson 指向数组的指针删除了它的第一个维度,引用不会
猜你喜欢
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多