Thread-Safe Queue - Problem
Implement a thread-safe bounded queue using mutexes and condition variables. The queue should support the producer-consumer pattern where multiple threads can safely enqueue and dequeue elements concurrently.
Your implementation should include:
- Bounded capacity: Queue has a maximum size limit
- Thread safety: Multiple threads can access simultaneously without race conditions
- Blocking operations: Producers block when queue is full, consumers block when queue is empty
- Proper synchronization: Use mutexes and condition variables for coordination
Implement the following operations:
enqueue(item): Add item to rear of queue (blocks if full)dequeue(): Remove and return item from front of queue (blocks if empty)size(): Return current number of items in queueis_full(): Return true if queue has reached capacityis_empty(): Return true if queue contains no items
Input & Output
Example 1 — Basic Operations
$
Input:
capacity = 3, operations = [["enqueue",10],["enqueue",20],["size"],["dequeue"],["is_empty"]]
›
Output:
[true,true,2,10,false]
💡 Note:
Create queue with capacity 3. Enqueue 10 (success), enqueue 20 (success), size is 2, dequeue returns 10, not empty.
Example 2 — Full Queue Behavior
$
Input:
capacity = 2, operations = [["enqueue",1],["enqueue",2],["is_full"],["enqueue",3],["dequeue"]]
›
Output:
[true,true,true,true,1]
💡 Note:
Fill queue to capacity 2, check is_full (true), third enqueue blocks until dequeue makes space.
Example 3 — Empty Queue Behavior
$
Input:
capacity = 1, operations = [["is_empty"],["enqueue",5],["dequeue"],["is_empty"]]
›
Output:
[true,true,5,true]
💡 Note:
Start empty (true), add 5, remove 5, back to empty (true).
Constraints
- 1 ≤ capacity ≤ 1000
- 1 ≤ operations.length ≤ 1000
- -106 ≤ item values ≤ 106
- All operations are valid within queue constraints
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code