C++ 向pthread函数传递和访问多个参数
我是cpp和线程的初学者。参考stackoverflow中的一些代码片段,将多个参数传递给pthread函数,并得出以下代码。我不知道如何使用传递给函数的void*指针访问函数内部的结构成员。有人能解释一下吗C++ 向pthread函数传递和访问多个参数,c++,pthreads,C++,Pthreads,我是cpp和线程的初学者。参考stackoverflow中的一些代码片段,将多个参数传递给pthread函数,并得出以下代码。我不知道如何使用传递给函数的void*指针访问函数内部的结构成员。有人能解释一下吗 #include <iostream> #include <pthread.h> #include <vector> using namespace std; struct a{ vector <int> v1; int val; };
#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的成员
您必须重新转换为从中转换的类型&args是a*.Use std::thread,而不是pthreads.Oops!知道了!谢谢
void* function(void *ptr)
{
a* args = static_cast<a*>(ptr);
args->v1.push_back(args->val);
return NULL;
}