将数组作为参数传递给std :: thread

时间:2015-12-08 21:23:58

标签: c++ arrays multithreading c++11

我很难使用std::thread将整数数组传递给函数。似乎线程不喜欢它的数组部分。还有什么方法可以将数组传递给线程函数?

#include <thread>
#include <ostream>
using namespace std;

void process(int start_holder[], int size){
  for (int t = 0; t < size; t++){
   cout << start_holder[t] << "\n";
  }
}
int main (int argc, char *argv[]){
  int size = 5;
  int holder_list[size] = { 16, 2, 77, 40, 12071};
  std::thread run_thread(process,holder_list,size); 
  //std::ref(list) doesnt work either
  //nor does converting the list to std::string then passing by std::ref
  run_thread.join();
} 

2 个答案:

答案 0 :(得分:1)

由于您使用的是C ++,因此开始使用std::vectorstd::list而不是c-style数组。还有许多其他container类型。如果你想要一个固定大小的数组,请改用std::array(因为C ++ 11)。

这些容器具有获取大小的功能,因此您无需将其作为单独的参数发送。

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

void process(std::vector<int> start_holder){
    for(int t = 0; t < start_holder.size(); t++){
       std::cout << start_holder[t] << "\n";
    }
    // Or the range based for
    for(int t: start_holder) {
       std::cout << t << "\n";
    }
}

int main (int argc, char *argv[]){
    std::vector<int> holder_list{ 16, 2, 77, 40, 12071};
    std::thread run_thread(process, holder_list); 
    run_thread.join();
}

答案 1 :(得分:0)

size保持不变:

#include <thread>
#include <iostream>

void process(int* start_holder, int size){
  for (int t = 0; t < size; t++){
   std::cout << start_holder[t] << "\n";
  }
}

int main (int argc, char *argv[]){
  static const int size = 5;
  int holder_list[size] = { 16, 2, 77, 40, 12071};
  std::thread run_thread(process, holder_list, size); 
  run_thread.join();
}

如果size是变量,int arr[size]不是标准C ++。它是语言的变量数组扩展名,正如编译器在错误中所说的那样,与int*又名int []不兼容。