繁体   English   中英

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

[英]Pass an array list as an argument to pthread_create

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

代码 :-

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

请让我知道我做错了什么,已经为此苦苦挣扎了一段时间,而且我对多线程并没有太多经验。 提前致谢。

问题是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);
}

暂无
暂无

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

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