Design a Blocking Queue (with logic + code)
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-04-18
Problem Statement
Designing a thread-safe blocking queue. This queue supports concurrent producers and consumers, and ensures that:
•Producers wait if the queue is full.
•Consumers wait if the queue is empty.
The focus is on concurrency, synchronization, and correctness.
✅ Functional Requirements
1.Queue Operations
•enqueue(item): Add an item to the queue.
•dequeue(): Remove and return an item from the queue.
2.Blocking Behavior
•If the queue is full, enqueue blocks until space is available.
•If the queue is empty, dequeue blocks until an item is available.
3.Thread Safety
•Support multiple producer and consumer threads simultaneously.
•Ensure no race conditions or deadlocks.
4.Optional Features
•Timeout for blocking operations.
•Peek operation to view the head item without removing.
•Maximum queue capacity configurable at runtime.
🔐 Constraints & Assumptions
•Focus on LLD and concurrency.
•Single-machine implementation (no distributed system).
•Items are generic objects (int, string, or custom type).
🧱 Key Components & Classes
1.BlockingQueue Class
1
2template <typename T>
3class BlockingQueue {
4private:
5 queue<T> q;
6 int capacity;
7 mutex mtx;
8 condition_variable cv_notFull;
9 condition_variable cv_notEmpty;
10
11public:
12 BlockingQueue(int cap) { capacity = cap; }
13
14 void enqueue(T item) {
15 unique_lock<mutex> lock(mtx);
16 cv_notFull.wait(lock, [this]{ return q.size() < capacity; });
17 q.push(item);
18 cv_notEmpty.notify_one();
19 }
20
21 T dequeue() {
22 unique_lock<mutex> lock(mtx);
23 cv_notEmpty.wait(lock, [this]{ return !q.empty(); });
24 T item = q.front();
25 q.pop();
26 cv_notFull.notify_one();
27 return item;
28 }
29
30 int size() {
31 unique_lock<mutex> lock(mtx);
32 return q.size();
33 }
34};🔄 Example Workflow
1.Producer Thread:
•Calls enqueue(item).
•If queue is full → blocks until space is available.
2.Consumer Thread:
•Calls dequeue().
•If queue is empty → blocks until an item is available.
3.Multiple threads:
•Thread-safe operations ensured using mutex and condition_variable.
🧪 Expected Deliverables
•Class diagram showing BlockingQueue and thread interactions.
•Implementation of enqueue and dequeue methods with blocking behavior.
•Test cases:
•Single producer and single consumer
•Multiple producers and multiple consumers
•Verify blocking behavior on full and empty queue
•Thread safety under high concurrency
💡 Discussion Points / Trade-offs
1.Locking Strategy
•Single mutex protects the queue → simple but may reduce concurrency.
•Separate locks for enqueue and dequeue → more complex but higher throughput.
2.Blocking vs Non-blocking
•Blocking ensures safety and simplicity for producer-consumer workflows.
•Non-blocking (tryEnqueue/tryDequeue) may be required for low-latency systems.
3.Capacity Management
•Fixed capacity avoids unbounded memory growth.
•Optionally allow dynamic resizing with care for race conditions.
4.Performance
•Condition variables minimize CPU usage compared to busy-waiting.
•Suitable for high-frequency concurrent producer-consumer workloads.
This problem tests LLD, concurrency, synchronization primitives, and blocking behavior, making it ideal for an LLD + multithreading interview round.