传递和访问多个参数到pthread函数

时间:2017-11-27 12:49:53

标签: c++ pthreads

我是cpp和线程的初学者。引用stackoverflow中的一些代码片段将多个参数传递给pthread函数,并提出以下代码。我不知道如何使用传递给它的(void *)指针访问函数内部的struct成员。谁能解释一下?

#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 *'不是指向对象的指针类型

1 个答案:

答案 0 :(得分:1)

在将a投回void*之前,您无法访问a*的成员。

void* function(void *ptr)
{
 a* args = static_cast<a*>(ptr);

 args->v1.push_back(args->val);
 return NULL;
}
相关问题