0

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
Damenace
  • 1
  • 2
  • `item` is uninitialised. – t0mm13b May 11 '17 at 00:02
  • the function produce_item returns a rand number up to 50 – Damenace May 11 '17 at 00:07
  • what about the `consume_item` ? – t0mm13b May 11 '17 at 00:10
  • `i` is uninitialised. – kaylum May 11 '17 at 00:11
  • consume_item does nothing but print out the item, I am unsure how to remove from buffer. – Damenace May 11 '17 at 00:12
  • But `item` is uninitalised when passed to `consume_item`. Too much missing code to be sure what is happening. Please provide a [mcve]. – kaylum May 11 '17 at 00:13
  • why do we need to initialize item when it is being creating before we consume it. Do i need to pass it in as an argument to the consumer function? – Damenace May 11 '17 at 00:16
  • Don't know what you mean. But generally if you are passing a variable to a function then that variable needs to have a valid value for the function to use right? `printf("Consumer consumes %d\n",item);` what do you expect that to print since `item` has not been set to any value? It is Undefined Behaviour. – kaylum May 11 '17 at 00:30

0 Answers0