My current code answers the producer consumer question, but I want to implement it in a different way. I do not want to use a global variable to keep track of the count in my buffer stack . What should my thought process be?
typedef int semaphore;
semaphore mutex, full, empty;
int count = 0;
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
int buffer[N];
These are the functions that use count
int remove_item()
{
int ret = buffer[--count];
buffer[count] = 0;
return ret;
}
void insert_item(int item)
{
buffer[count++] = item;
}
int produce_item(){
int item = rand()%50 +1;
printf("Producer produces %d\n",item);
sleep(1);
return item;
}
And my producer consumer functions
void* consumer(void * arg) {
int item = 0;
while(1){
down(full);
down(mutex);
item = remove_item();
buffer[count++] = item;
up(mutex);
up(empty);
consume_item(item);
}
return 0;
}
void* producer(void* arg) {
int item, i =0;
while(1){
item = produce_item();
down(empty);
down(mutex);
insert_item(item);
up(mutex);
up(full);
sleep(1);
}