I am a beginner to cpp and threads. Referred to some code snippets in stackoverflow to pass multiple arguments to a pthread function and came up with the below code. I am not sure how to access the struct members inside the function using (void*) pointer passed to it. Can anyone explain?
#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;
}
Getting the error : error: 'void*' is not a pointer-to-object type
You cannot access the members of a
until you have cast the void*
back to an a*
.
void* function(void *ptr)
{
a* args = static_cast<a*>(ptr);
args->v1.push_back(args->val);
return NULL;
}
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.