Producer Consumer Problem in C

Here you will learn about producer consumer problem in C.

Producer consumer problem is also known as bounded buffer problem. In this problem we have two processes, producer and consumer, who share a fixed size buffer. Producer work is to produce data or items and put in buffer. Consumer work is to remove data from buffer and consume it. We have to make sure that producer do not produce data when buffer is full and consumer do not remove data when buffer is empty.

Also Read: Banker’s Algorithm in C

The producer should go to sleep when buffer is full. Next time when consumer removes data it notifies the producer and producer starts producing data again. The consumer should go to sleep when buffer is empty. Next time when producer add data it notifies the consumer and consumer starts consuming data. This solution can be achieved using semaphores.

producer consumer problem in c

Image Source

You can watch below video to learn more about this problem.

Producer Consumer Problem in C

Below is the program to implement this problem.

 

Output

1.Producer
2.Consumer
3.Exit
Enter your choice:1

Producer produces the item 1
Enter your choice:2

Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:1

Producer produces the item 1
Enter your choice:1

Producer produces the item 2
Enter your choice:1

Producer produces the item 3
Enter your choice:1
Buffer is full!!
Enter your choice:3

11 thoughts on “Producer Consumer Problem in C

  1. @Ruthvick

    Hey why shouldn’t you publish readers writers using semaphores?

    Reply
    1. tasneem mallah

      if we have to determine number of producer and consumer for example (3 producer & 3 consumer )
      how we can do it ??
      and if we have to use mutixes rather than semaphore how we can do it ?

      Reply
  2. Poulami

    Sir what is the prototype of exit? I have 1 error tat “‘exit should have a prototype”

    Reply
  3. cowboy

    why have you used mutex when it doesnt make a difference to the execution ????

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *