传递给 pthread 函数调用后访问结构成员

Access Struct members after pass to pthread function call

我正在尝试访问传递给 pthread 进程调用的函数的结构成员。这很简单,但由于某种原因我无法弄清楚。

我试过使用 data.count 或 data->count,但我想我需要将我的数据指针转换为传递给它的结构?我很困惑,但我相信解决方案很简单。请帮忙。 这是结构,后面是 pthread 调用和正在使用的函数。谢谢。 我可以补充一点,BUFFER_SIZE 是全局定义的,所以根据我的理解,这不是问题。我没有在代码中分享。

typedef struct {
        int buffer[BUFFER_SIZE];
        int count;
        int top;
        int next;
        pthread_mutex_t count_lock;
} prodcons;

//this is in main.c
prodcons pc_nums;

//create producer thread
pthread_create(&tid, &attr, *producer, &pc_nums);

//This is the runner function, pthread call this
void *producer(void *data)
{
        //set up data structure to be shared between producer and       consumer
        int number;
        prodcons primeNums;
        pc_init(&primeNums);

        //call consumer thread
        pthread_t tid;
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_create(&tid, &attr, *consumer, &primeNums);

        while (data->count < BUFFER_SIZE)
        {
                number = pc_pop(data);
                factor2pc(&primeNums, number);
        }
}

我只是希望访问我的 pthread_create 传递的结构中的变量,但我得到了 错误:'count' 不是某些结构或联合的一部分。 我真的需要弄清楚如何使数据指向我的结构,以便我可以访问它的成员

简短版本:是的,您必须将 'data' 转换为正确的类型:

void producer(void *data_p) {
    prodcons *data = data_p ;
    ... rest of your code ...
} ;

旁注:小心 'pc_nums' 的存储 class。在多线程程序中,main 可能会自行终止(pthread_exit),或者自动变量会被释放。从您的示例中不清楚产品是如何分配的。如果 prodcons 是 'auto' 变量(本地),请考虑将其设为静态,或者在需要时使用 malloc/calloc 为其分配堆 space。