I'm trying to write a program in C where I remove, add, and initialize a bounded buffer for the consumer/producer problem. Here's what my bounded buffer program looks like:
Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bbuffer.h"
int count;
pthread_mutex_t mutex;
int in, out;
int bounded_buffer[BOUNDED_BUFFER_SIZE];
void initialize_bounded_buffer() {
int status;
count = 0;
pthread_mutex_lock(&mutex);
status = pthread_mutex_init(&mutex, NULL);
if (status != 0) {
fprintf(stderr, "Error creating buffer_mutex\n");
}
pthread_mutex_unlock(&mutex);
}
void add_to_buffer(int value) {
pthread_mutex_lock(&mutex);
while (count == BOUNDED_BUFFER_SIZE){
//make it wait
}
if (count < BOUNDED_BUFFER_SIZE) {
bounded_buffer[count] = value;
count++;
printf("added");
} else {
printf("buffer full");
}
pthread_mutex_unlock(&mutex);
}
int remove_from_buffer() {
for (;;){
pthread_mutex_lock(&mutex);
while (count == 0) {
//make it wait
}
if (count > 0){
bounded_buffer[count] = bounded_buffer[count-1];
count--;
printf("removed");
return 0;
} else {
printf("could not remove");
return -1;
}
pthread_mutex_unlock(&mutex);
}
}
Now one thing that confuses me is that in order to implement this I need to use two condition variables but I'm not sure what the condition variables would be used for and how they would work for adding/removing an item from the bbuffer. I'm also trying to implement a better way for the program to wait as opposed to just having an infinite while loop.
Also here's my bbuffer.h file:
Code:
#ifndef _BBUFFER_H_
#define _BBUFFER_H_
#define BOUNDED_BUFFER_SIZE 4
void initialize_bounded_buffer();
void add_to_buffer(int);
int remove_from_buffer();
#endif