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 queue
  • is_full(): Return true if queue has reached capacity
  • is_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
INPUT: Queue Setup1020emptyfrontrearCapacity: 3, Count: 2Circular array with front/rear pointersALGORITHM: Synchronization1Acquire mutex lock2Check queue conditions3Wait on condition variable4Perform operation safely🔒 Thread-SafeRESULT: Thread CoordinationProducer-Consumer PatternProducerConsumerEnqueueDequeue🔔 Condition Variables:• not_full (producers wait)• not_empty (consumers wait)✅ No Race Conditions✅ Efficient BlockingKey Insight:Mutex locks ensure thread safety while condition variables provide efficient blocking,creating the perfect producer-consumer pattern without busy-waiting or race conditions.TutorialsPoint - Thread-Safe Queue | Mutex + Condition Variables
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18 Apple 15
25.0K Views
Medium Frequency
~35 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen