Producer Consumer¶
Producer Consumer is another classic shared concurrency problem when there are two classes of threads that share a common resource (such as a queue) of a fixed size. Producers are threads that add elements to the back of the queue, while consumers remove elements from the front. If there are no elements to remove, the consumers wait (or block) until new elements are added. If the queue is full, the producers wait (or block) until some elements are removed from the queue, freeing up space.
In the videos below, the producers and consumers share access to a circular buffer, a special type of queue where there is no explicit front or back.
Watch the full video here:
One Producer, One Consumer¶
This video illustrates the case where a single producer thread and a single consumer thread share access to a circular buffer:
Five Producers, Five Consumers¶
Here is a more elaborate example where there are 5 producer threads and five consumer threads all sharing access to a circular buffer.