如何正确地将向量<int>转换为空隙*并返回向量<int>?

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

本文关键字:lt gt int 向量 返回 正确地 转换      更新时间:2023-10-16

说明

我需要将向量转换为 void*,以便我可以将其作为参数传递到通过 pthread 调用的函数中。在该函数中,我需要将 void* 转换回向量才能访问其元素。

法典

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

问题

我不明白为什么 v 包含 2 个单独的向量。此外,有效值在 v1 和 v2 之间旋转;有时一个是垃圾,另一个具有有效值。这是我的转换/转换问题还是线程同步的更大问题?

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

void* compare(void* x) {
    vector<int> v = ((vector<int>*)x)[0];
    cout << v[0] << " " << v[1] << " " << v[2];
}

输出:

1 2 3

在此示例中v1指针指向矢量而不是矢量本身。它是指针的基址。当你取v1[0]时,你取的是实际的向量。您已将矢量(不是矢量(的地址传递给 pthread (&x)这就是为什么您需要将其类型转换为矢量指针,然后是矢量。

错误的问题。 使用 std::thread ,它知道如何处理参数类型:

void f(std::vector<int>& arg);
int main() {
    std::vector<int> argument;
    std::thread thr(f, std::ref(argument));
    thr.join();
    return 0;
}