I am attempting to pass an Array List as below as an argument to a class member thread function which in turn calls another member function but i am failing to retrieve the values inside the thread function.
Code :-
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);
}
Please let me know what i'm doing wrong, been struggling with this for a while and I am not too experienced with Multithreading. Thanks in advance.
The problem is that Coordinates
is passed void *
so there is ONLY one address stored. No size of initial array. You MUST pass size extra, by passing custom struct, std::pair
or std::vector
or append something that is invalid coordinate and stop on that.
If you can use std::vector
and so on you can do it like this (just pass vector by pointer):
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.