I have a question on how to implement using a shared memory buffer in semaphore sets. I am doing the classic consumer producer problem where I add a new item to a buffer stack and depending on the scheduler I want to remove the first in item produced from my producer. Below is my producer and consumer code :
int produce_item(){
int item = rand()%50 +1;
printf("Producer produces %d\n",item);
sleep(1);
return item;
}
void consume_item(int item){
printf("Consumer consumes %d\n",item);
sleep(2);
}
void* consumer(void * arg) {
int item, j=0;
while(1){
down(full);
down(mutex);
consume_item(item);
buffer[j++] = item;
up(mutex);
up(empty);
}
return 0;
}
void* producer(void* arg) {
int item, i;
while(1){
item = produce_item();
down(empty);
down(mutex);
buffer[i++]=item;
up(mutex);
up(full);
sleep(1);
}
my buffer is decalred as a global variable
and here is a test run which shows my question, why is it only consuming the same item over and over again?
Consumer consumes 32622
Producer produces 16
Consumer consumes 32622
Producer produces 22
Consumer consumes 32622
Producer produces 1
Consumer consumes 32622
Producer produces 16
Consumer consumes 32622
Producer produces 15