HotWheels
HotWheels

Reputation: 444

C pthreads threads not executing functions for producer-consumer problem

Hi I am trying to implement an solution to producer consumer problem with threads and semaphores.

I have the two functions that the threads consumer and producer will call but they aren't executing. I am not sure what I am doing wrong as I am not getting any errors, my program is just not executing the thread functions. I am creating and joining the thread, I am not sure what is causing the issue

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
#include <errno.h> 
#include "buffer.h"

struct bufferStruct *item; //calls buffer structure from buffer.h
pthread_mutex_t mutex; //lock for synchronizing execution of threads(producer and consumer)
sem_t empty; //indicates buffer is empty
sem_t full;  //indicates buffer is full 
int input = 0;
int newitem;
pthread_attr_t attr;



void *producer(void *param)
{
   
    for(int i = 0; i < 5; i++)
    {
        sem_wait(&empty);
        pthread_mutex_lock(&mutex);
        newitem = rand();
        item->content[item->in] = newitem;
        printf("Producer prouced item %d at position %d in buffer\n", newitem, item->in);
        item->in = (item->in+1) % MAX_SIZE;
        pthread_mutex_unlock(&mutex);
        sem_post(&full);
        sleep(1);
    }
}

void *consumer(void * param)
{
    for(int i =0; i< 5; i++)
    {
        sem_wait(&full);
        pthread_mutex_lock(&mutex);
        newitem = item->content[item->out];
        printf("Consumer has consumed item %d at position %d in buffer\n", newitem, item->out);
        item->out = (item->out+1) % MAX_SIZE;
        pthread_mutex_unlock(&mutex);
        sem_post(&empty);
        sleep(1);
    }
}


int main()
{
   int initval = 1;
   int initval2 = 2;
   sem_init(&full, 1, 0);
   sem_init(&empty, 1, MAX_SIZE);
   if(pthread_mutex_init(&mutex,NULL)!=0){
       printf("Mutex init failed\n");
       return 1;
   }
   pthread_attr_init(&attr);
   pthread_t thread_produce, thread_consume;
   printf("Starting threads...\n");
   pthread_create(&thread_produce, &attr, producer, (void*)&(initval));
   pthread_create(&thread_consume, &attr, consumer, (void*)&(initval2));
   pthread_join(thread_produce, NULL);
   pthread_join(thread_consume, NULL);
   printf("Threads done executing...\n");
   pthread_mutex_destroy(&mutex);
   sem_destroy(&empty);
   sem_destroy(&full);
   exit(0);
}

Upvotes: 0

Views: 155

Answers (1)

John Bollinger
John Bollinger

Reputation: 180201

You declare

struct bufferStruct *item;

then you use item without ever assigning it to point to anything. Undefined behavior results.

If I fix that (first synthesizing a version struct bufferStruct and choosing a MAX_SIZE) then the program compiles without error and seems to run successfully.

Upvotes: 2

Related Questions