[英]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. 我需要将向量转换为void *,以便可以将其作为参数传递给通过pthread调用的函数。 In that function, I need to convert the void* back to a vector in order to access it's elements.
在该函数中,我需要将void *转换回向量,以便访问其元素。
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. 我不明白为什么v包含2个单独的向量。 Furthermore, the valid values rotate between v1 and v2;
此外,有效值在v1和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: <g>使用
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;
}
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. 在此示例中,
v1
是指向矢量的指针,而不是矢量本身。 It is base address of pointer. 它是指针的基地址。 When you take
v1[0]
then you take the actual vector. 当采用
v1[0]
则采用实际向量。 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. 您已将向量(不是向量)的地址传递给pthread
(&x)
,这就是为什么您需要先将其类型转换为向量指针,然后再向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.