Reputation: 547
Description
I need to convert a vector to a void*, so that I can pass it as a parameter in a function called via pthread. In that function, I need to convert the void* back to a vector in order to access it's elements.
Code
void* compare(void* x) {
vector<int>* v = (vector<int>*)x;
vector<int> v1 = v[0];
vector<int> v2 = v[1];
...
}
int main() {
...
vector<int> x = {1, 2, 3, 4};
pthread_create(&threads[i], NULL, compare, static_cast<void*>(&x));
...
}
Problem
I do not understand why v contains 2 separate vector. Furthermore, the valid values rotate between v1 and v2; sometimes one is junk and the other has valid values. Is this an issue with my casting/conversion or a greater problems with the synchronization of my threads?
Upvotes: 2
Views: 1747
Reputation: 76458
Wrong question. <g> Use std::thread
, which knows how to deal with argument types:
void f(std::vector<int>& arg);
int main() {
std::vector<int> argument;
std::thread thr(f, std::ref(argument));
thr.join();
return 0;
}
Upvotes: 1
Reputation: 2179
void* compare(void* x) {
vector<int>* v1 = (vector<int>*)(x);
vector<int> v = v1[0]; // it will always be v[0]
cout << v[0] << " " << v[1] << " " << v[2];
}
int main() {
pthread_t thread;
vector<int> x = {1, 2, 3, 4};
pthread_create(&thread, NULL, compare, static_cast<void*>(&x));
pthread_join( thread, NULL);
}
or
void* compare(void* x) {
vector<int> v = ((vector<int>*)x)[0];
cout << v[0] << " " << v[1] << " " << v[2];
}
Output:
1 2 3
In this example v1
is pointer to vector not vector itself. It is base address of pointer. When you take v1[0]
then you take the actual vector. You have passed address of vector (not vector) to pthread (&x)
that is why you need to typecast it to vector pointer and then vector.
Upvotes: 1