将数组列表作为参数传递给pthread_create

时间:2020-03-10 09:07:55

标签: c++ multithreading arraylist

我试图将以下数组列表作为参数传递给类成员线程函数,该成员成员函数依次调用另一个成员函数,但我无法在线程函数内部检索值。

代码:-

 pthread_t t2;
 int Coordinates[] = {(0,0), (1,1), (2,2)};
 pthread_create(&t2, NULL, &Class::thread_func,(void*) Coordinates);


void* Class::thread_func(void *arg)
{
  int *coord = (int *) arg;
  for(int i=0; i< sizeof(coord); i++)
  {
  classObj->doSomething(coord[i][0], coord[i][1]);
  }
  pthread_exit(0);
}

请让我知道我在做什么错,已经为此苦苦挣扎了一段时间,而且我对多线程处理还不太熟悉。 预先感谢。

1 个答案:

答案 0 :(得分:0)

问题是Coordinates被传递给void *,所以只存储了一个地址。没有初始数组的大小。您必须通过传递自定义结构std::pairstd::vector来额外传递大小,或附加无效坐标并停止该坐标。

如果您可以使用std::vector,依此类推(只需通过指针传递矢量)即可。

void* thread_func(std::vector<std::array<int, 2>> *coord) {
  for(int i=0; i < coord->size(); i++)
  {
    cout << (*coord)[i][0] << " " << (*coord)[i][1]<<endl;;
  }
  pthread_exit(0);
}

int main(){
  pthread_t t2;
  std::vector<std::array<int, 2>> Coordinates= {{0,10}, {1,11}, {2,22}};
  pthread_create(&t2, NULL, (void * (*)(void *))thread_func, &Coordinates);
  pthread_join(t2, NULL);
}
相关问题