简体   繁体   中英

How to properly convert a vector<int> to a void* and back to a vector<int>?

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?

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

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.

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