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

 

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

34 thoughts on “Producer Consumer Problem in C”

    1. 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 ?

  1. @NeerajMishra actully the code and the video itself dont match. In the video the dude is explaining how to implement thye code using Semaphores. But the code that you provided us is the one which is implemented using Mutex.
    1. You should provide us with the explanation of your code (using mutex)
    or 2. You should provide us the code based on the video (using semaphores)
    thanks anyways!

  2. Why you declare mutex variable to increment at the beginning of producer and consumer and decrement at the end of producer and consumer? If you remove mutex variable it works fine.

  3. Your program is fundamentally flawed!!
    The whole idea is to carry out transactions (on the buffer) atomically, which is only possible using process synchronisation. Threads have not been used at all! The CPU scheduler is responsible for choosing which process to execute next.

  4. Thank you for your explanation.
    Is it possible to separate consumer and producer in two different classes, let them access to a shared array/buffer and compile as followed?

    $ gcc producer.c -pthread -lrt -o producer

    $ gcc consumer.c -pthread -lrt -o consumer

    $ ./producer & ./consumer &

Leave a Comment

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