【问题标题】:Passing array as argument to std::thread将数组作为参数传递给 std::thread
【发布时间】:2016-03-13 23:41:57
【问题描述】:

我在使用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();
} 

【问题讨论】:

  • 如果你要为你的变量使用标准库名称,不要说using namespace std;。其实还是不要说出来了。
  • 这实际上是std::thread 的问题,还是int list[size] = { 16, 2, 77, 40, 12071};,尽管有VLA 扩展,但它不适用于Clang?
  • 好的,知道如何解决这个问题吗?
  • 我认为这是 std::thread 的问题。我应该改用 pthread 并将数组放入结构中吗?
  • size的类型更改为const int

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


【解决方案1】:

由于您使用的是 C++,因此请开始使用 std::vectorstd::list 而不是 c 样式的数组。还有许多其他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();
}

【讨论】:

    【解决方案2】:

    使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* aka int [] 不兼容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-05
      • 2016-04-16
      • 1970-01-01
      • 2020-12-15
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多