Blocking Queue | Bounded Buffer | Consumer Producer
Explore the implementation of blocking queues and bounded buffers in C#. Understand how to handle consumer-producer problems using mutex locks to control access and avoid race conditions. Learn to build thread-safe enqueue and dequeue methods and grasp the challenges of waiting, signaling, and busy-wait loops.
Blocking Queue | Bounded Buffer | Consumer Producer
A blocking queue is defined as a queue which blocks the caller of the enqueue method if there's no more capacity to add the new item being enqueued. Similarly, the queue blocks the dequeue caller if there are no items in the queue. Also, the queue notifies a blocked enqueuing thread when space becomes available and a blocked dequeuing thread when an item becomes available in the queue.
Solution
The bounded buffer is a classic textbook concurrency problem. We'll look at the various ways we can implement such a buffer.
Our queue will have a finite size that is passed in via the constructor. Additionally, we'll use an integer array as the data structure for backing our queue. We choose to use a simple integer array to make the example easier to follow. However, a solution with a generic container would follow the same underlying logic.
Furthermore, we'll expose two APIs in our blocking queue class:
enqueue()...