0
votes

I am trying to access members of my struct that is passed to a function that was called by a pthread process. It is simple, but for some reason I cannot figure it out.

I have tried using data.count or data->count, but I guess I need to cast my data pointer to my struct that passed to it? I am very confused, but I am sure the solution is simple. please help. Here is the struct, followed by the pthread call and the function being used. Thanks. I can add that BUFFER_SIZE is defined globally so that is not a problem from my understanding. I did not share that in the code.

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);
        }
}

I just expect to access the variables in my struct passed by my pthread_create, but I am getting error: 'count' not part of some structure or union. I really need to just figure out how to make data point to my structure so I can access its members

1

1 Answers

0
votes

Short version: Yes, you have to cast 'data' to the right type:

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

Side note: Be careful with the storage class of 'pc_nums'. In Multi-Threaded program, it is possible for the main to terminate itself (pthread_exit), or for automatic variables to be released. It;s not clear from your example how prodcons is allocated. If prodcons is 'auto' variable (local), consider making it static, or use malloc/calloc to allocate heap space for it, if needed.