我是 cpp 和线程的初学者。引用了 stackoverflow 中的一些代码片段以将多个参数传递给 pthread 函数并得出以下代码。我不确定如何使用传递给它的 (void*) 指针访问函数内部的结构成员。谁能解释一下?
#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;
struct a{
vector <int> v1;
int val;
};
void* function(void *args)
{
vector <int>functionvector = (vector <int>)args->v1;
functionvector.push_back(args->val);
return NULL;
}
int main()
{
pthread_t thread;
struct a args;
pthread_create(&thread, NULL, &function, (void *)&args);
pthread_join(thread,NULL);
for(auto it : args.v1)
{
cout<<it;
}
return 0;
}
获取错误: 错误:“void*”不是指向对象类型的指针
最佳答案
在将 void*
转换回 a*
之前,您无法访问 a
的成员。
void* function(void *ptr)
{
a* args = static_cast<a*>(ptr);
args->v1.push_back(args->val);
return NULL;
}
关于c++ - 向 pthread 函数传递和访问多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511409/