0

Hi I'm trying to write an algorithm for solving the producer-consumer problem and I've hit a roadblock. This is the output I am getting from my code:

Producing: 6 6 0 0 0 0 0 0 0 0 0 END

and then the program exits. I'm not sure where I went wrong? Did I do something wrong in creating a circular buffer?

#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h> 
#include <stdio.h>
#include <string>
#include <fstream>
using namespace std;

#define BUFFER_SIZE 10

void *produce(void *);
void *consume(void *);
int produceItem(void);
void insertItem(int item);
void removeItem(void);
void printBuffer(void);

int head = 0;
int tail = 0;
int item;
int bufferCount = 0;
pthread_t producer, consumer;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock;
sem_t sem_filledSlots;
sem_t sem_emptySlots;
int buffer[BUFFER_SIZE];


int main() {

    int emptyCount;
    int item;
    srand (time(NULL));


    sem_init(&sem_filledSlots, 0, 0);
    sem_init(&sem_emptySlots, 0, BUFFER_SIZE);

    sem_getvalue(&sem_emptySlots, &emptyCount);


    pthread_create (&producer, NULL, &produce, NULL);
    pthread_create (&consumer, NULL, &consume, NULL);


    return 0;
}

void *produce(void *)
{

    for(int i = 0; i <15; i++)
    {
        item = produceItem();
        sem_wait(&sem_emptySlots);
        pthread_mutex_lock(&lock);
        printf("Producing: %d \n", item);
        buffer[head] = item;
        head = (head + 1) % BUFFER_SIZE;
        printBuffer();
        pthread_mutex_unlock(&lock);
        sem_post(&sem_filledSlots);
    }
}

void *consume(void *)
{
    for(int i = 0; i <15; i++)
    {
        sem_wait(&sem_filledSlots);
        pthread_mutex_lock(&lock);
        printf("Consuming %d \n", buffer[tail]); 
        buffer[tail] = 0;
        tail = (tail + 1) % BUFFER_SIZE;
        bufferCount--;
        printBuffer();
        pthread_mutex_unlock(&lock); 
        sem_post(&sem_emptySlots);
    }
}

int produceItem(void)
{

    int x = (rand()%11 + 1);
    return x;
}

void printBuffer(void)
{

    for(int i = 0; i <BUFFER_SIZE; i++)
    {

        printf("%d ", buffer[i]);

    }
    printf("END \n");
}
user2134127
  • 135
  • 1
  • 2
  • 9

1 Answers1

0

you're missing pthread_join before exiting the program:

.... pthread_join(producer,NULL); pthread_join(consumer,NULL); return 0; ....

andrjas
  • 260
  • 1
  • 5