Blocking insert using multithreading if queue is full (thread synchronization logic)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-05-08

Problem Statement

Design and implement a bounded blocking queue that supports multiple producer and consumer threads. The queue must have a fixed capacity and use thread synchronization primitives to handle concurrent operations safely.


Functional Requirements


•Implement two primary APIs:
1.enqueue(item) → Inserts an item into the queue.
•If the queue is full, the producer thread should block until space becomes available.
2.dequeue() → Removes and returns an item from the queue.
•If the queue is empty, the consumer thread should block until an item is available.
•The queue should be thread-safe and support multiple producers and multiple consumers.
•Must ensure fairness so that no thread starves indefinitely.


Non-Functional Requirements


•Use only basic synchronization constructs (mutex/lock, condition variable, or semaphores).
•Minimize context switches for performance.
•Ensure correctness under high concurrency.


Design Hints


•Maintain a buffer (circular queue / list) to store items.
•Use a mutex/lock to ensure only one thread modifies the queue at a time.
•Use two condition variables (or equivalent):
•notFull → signals producers when space is available.
•notEmpty → signals consumers when items are available.
•Ensure proper wait–notify handling to avoid deadlocks.


Solution

Comments