我试图将以下数组列表作为参数传递给类成员线程函数,该成员成员函数依次调用另一个成员函数,但我无法在线程函数内部检索值。
代码:-
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);
}
请让我知道我在做什么错,已经为此苦苦挣扎了一段时间,而且我对多线程处理还不太熟悉。 预先感谢。
答案 0 :(得分:0)
问题是Coordinates
被传递给void *
,所以只存储了一个地址。没有初始数组的大小。您必须通过传递自定义结构std::pair
或std::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);
}