简体   繁体   English

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

[英]Passing array as argument to std::thread

I'm having difficulty passing an array of integers to a function using std::thread . 我很难使用std::thread将整数数组传递给函数。 It seems like thread doesn't like the array portion of it. 似乎线程不喜欢它的数组部分。 What other way is there to pass an array to a threaded function? 还有什么其他方法可以将数组传递给线程函数?

#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();
} 

Since you are using C++ start using std::vector or std::list instead of the c-style arrays. 由于您使用的是C ++,因此开始使用std :: vectorstd :: list而不是c样式的数组。 There are many other container types as well. 还有许多其他容器类型。 If you want a fixed size array use std::array instead (since C++11). 如果要固定大小的数组,请改用std :: array (因为C ++ 11)。

These containers have functions to get the size so you do not need to send it through as a separate argument. 这些容器具有获取大小的功能,因此您无需将其作为单独的参数发送出去。

#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();
}

Make size constant: 使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();
}

If size is variable, int arr[size] is not a standard C++. 如果size是可变的,则int arr[size]不是标准的C ++。 It is a variable array extension to the language as your compiler says in the error and is not compatible with int* aka int [] . 正如编译器在错误中所述,它是该语言的可变数组扩展,并且与int* aka int []不兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM