c++ - 向 pthread 函数传递和访问多个参数

标签 c++ pthreads

我是 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/

相关文章:

c++ - 错误 C2440 '=' : cannot convert from 'cli::array<Type> ^' to 'wchar_t'

c++ - VeridisBiometricSDK_5.0_Linux 示例: MatchingExample 编译错误

c++ - 在网站上:godbolt.org,只有在那里:如何使用 std::thread?

c++ - CMake 链接错误 pthread:启用多线程以使用 std::thread:不允许操作

c++ - pthread_cond_wait 没有从 pthread_cond_broadcast 唤醒

c - 如何使用条件变量

c++ - 出于什么原因,具有 void 返回类型的函数会是 constexpr?

c++ - 来自 bitset<n> 的有符号整数

c++ - CLion 不显示 C++ SDL2 的输出

linux - 在 pthreads 线程的堆栈中预先设置故障的最佳方法是什么?