【问题标题】:Struct loses track of variables when using pthread_create使用 pthread_create 时,Struct 会丢失对变量的跟踪
【发布时间】:2018-05-12 17:04:53
【问题描述】:

我正在尝试创建一个运行名为 csvSearch 的函数的新线程。该函数需要 3 条信息,因此我将它们放入一个结构中。

csvSearch 将(void *) 作为其参数,当将该指针转换回指向该结构的指针时,不知何故我丢失了存储在outpath 和column 这两个结构字段中的数据。

这是结构定义:

typedef struct {
    char path[256];
    char outpath[256];
    char column[32];
} Data;

创建线程时我使用了以下代码

Data *data = malloc(sizeof(Data *));

strcpy(data->path, path);
strcpy(data->outpath, outpath);
strcpy(data->column, column);

pthread_create(&threads[threadCount], NULL, csvSearch, data);

这是我试图调用的函数 csvSearch 的摘要

void *csvSearch(void * data){

    Data * input = (Data *) data;

    char * path = input->path;
    char * outpath = input->outpath;
    char * column = input->column;

//path is the correct string, but outpath and column are both empty strings
}

我已经使用 gdb 对此进行了广泛的测试,但一直无法找到问题所在。我知道直到pthread_create,数据包含正确的信息,并且当它被转换回Data * 时,我得到相同的内存地址和大小,但是input->outpath 和input->column 都填充了空字符。

我的语法有什么不正确的吗?还是不能以这种方式将信息传递给新线程中的函数?

【问题讨论】:

  • 很好地介绍了这个问题。

标签: c multithreading memory struct pthreads


【解决方案1】:
Data *data = malloc(sizeof(Data *));

正在为Data* 而不是Data 分配内存。您需要

Data *data = malloc(sizeof(Data));

【讨论】:

  • 或者更好的是,使用sizeof *data。
猜你喜欢
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
相关资源
最近更新 更多