c - 读取时传递到 pthread_create 的结构数据不正确

标签 c pthreads

在下面的代码中,我尝试将一个结构传递到pthread_create中。该结构体是全局定义的。然后在调用 pthread_create 之前对其进行初始化。

// Global scope
struct dat_struct {
  char *dat[SIZE];
  int received[SIZE];
  int numreceived;
};

 // main
  struct dat_struct *data = malloc(sizeof(struct dat_struct));


  for (int i=0; i < nthreads; i++) {
    for (int j=0; j < SIZE; j++) {
      data->received[j] = SIZE;
    }
    data->numreceived = 0;
    pthread_create(&thread_ids[i], NULL, thread_handler, (void*)&data);
  }

void *thread_handler(void *dat) {
  struct dat_struct *data = (struct dat*)dat;
  // If I read data->numreceived it returns a large negative or
  // something incorrect
  ...
  ...

thread_handler中,读取数据会给出错误的结果。如果我使用 gdb 检查传递给 pthread_create 的内容,它与另一端收到的内容不同。

我的代码中是否存在根本问题?

最佳答案

给定

struct dat_struct *data

这段代码

pthread_create(&thread_ids[i], NULL, thread_handler, (void*)&data);

struct dat_struct **作为void *传递给线程。请注意双**

因此这是错误的:

void *thread_handler(void *dat) {
  struct dat_struct *data = (struct dat*)dat;

该代码将 dat 视为 struct dat_struct * - 但您传递了 struct dat_struct **。 (我假设 (struct dat*) 是一个打印错误)。

您应该使用以下内容创建线程

pthread_create(&thread_ids[i], NULL, thread_handler, data);

void *thread_handler(void *dat) {
  struct dat_struct *data = dat;

请注意,无需在 C 中与 void * 进行转换。

关于c - 读取时传递到 pthread_create 的结构数据不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58273420/

相关文章:

c - 为什么所有指向结构的指针都必须具有相同的大小?

c - 如何在汇编代码中使用c变量

c - 是否通过 C99 中未指定的 union 进行类型双关,并已在 C11 中指定?

c - 使用pthread执行矩阵乘法

c++ - 程序终止时清理 pthread 资源

c - 将文件描述符传递给线程并在函数中使用它(作业)

c++ - 带有 phreads 的程序可以工作一段时间然后停止

无法调用参数中有空格的系统

c - -wrap 选项的 GNU 链接器通配符

c++ - 线程取消 (pthread) & C++