Blocking queue with multiple producers

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-11-11

Problem Statement

Design and implement a thread-safe blocking queue data structure that supports multiple producers adding items concurrently and multiple consumers retrieving items concurrently. If the queue is full, producers should block until space becomes available; if the queue is empty, consumers should block until items are added.


Functional Requirements (FR)


Enqueue (put)


•Allows a producer thread to insert an item into the queue.
•If the queue is full, the producer should block until space is available.


Dequeue (take)


•Allows a consumer thread to remove and return an item from the queue.
•If the queue is empty, the consumer should block until an item is available.


Concurrency


•Support multiple producers inserting items concurrently.
•Support multiple consumers removing items concurrently.


Queue Size


•Queue has a fixed capacity defined at initialization.


Thread Safety


•All operations (put, take) must be synchronized to prevent race conditions.


Non-Functional Requirements (NFR)


•Performance: Ensure high throughput with multiple producers/consumers.
•Fairness: Ensure fair ordering (FIFO) and avoid starvation.
•Scalability: Should handle large numbers of producer/consumer threads.


Core Entities & Attributes


•BlockingQueue<T>
•Attributes: queue[], capacity, lock, notFull, notEmpty (condition variables).
•Methods:
•put(item: T)
•take(): T
•size(): int


Example Use Case


•Queue capacity = 3.
•Producer1 adds A, Producer2 adds B, Producer3 adds C → queue full [A, B, C].
•Producer4 tries to add D → blocks until a consumer removes an element.
•Consumer1 takes A → queue [B, C] → Producer4 resumes and adds D.


Evaluation Criteria


•Correct handling of blocking behavior on empty/full conditions.
•Thread-safety across multiple producers and consumers.
•Clean synchronization design (locks, condition variables, or semaphores).
•FIFO ordering maintained.


Solution

Comments