Write a program for producer-consumer problem

Write a program for producer-consumer problem. Use a blocking queue.

💡Strategies for Solving This Problem

Classic Concurrency Problem

Got this at Microsoft in 2023. It's one of the fundamental threading problems that every programmer should know. Tests your understanding of synchronization, race conditions, and thread safety.

The Problem

You have producers that generate data and consumers that process it. They share a bounded buffer (fixed size queue). Producers add items, consumers remove items. Need to handle:

  • Buffer full: Producer must wait
  • Buffer empty: Consumer must wait
  • Thread safety: No race conditions
  • No deadlocks or busy waiting

Why It's Important

This pattern appears everywhere in real systems:

  • Web servers handling requests
  • Message queues (Kafka, RabbitMQ)
  • Thread pools
  • Event processing systems

Naive Approach: Polling

Busy-wait loops checking if buffer has space or items. Wastes CPU cycles. Never do this in production.

Better: Locks and Condition Variables

Use mutex for thread safety and condition variables to sleep/wake threads efficiently.

Key components:

  • Mutex: Protects shared buffer from concurrent access
  • notFull condition: Signals when buffer has space
  • notEmpty condition: Signals when buffer has items

The Pattern

Producer:

  1. Lock mutex
  2. While buffer full, wait on notFull
  3. Add item to buffer
  4. Signal notEmpty
  5. Unlock mutex

Consumer:

  1. Lock mutex
  2. While buffer empty, wait on notEmpty
  3. Remove item from buffer
  4. Signal notFull
  5. Unlock mutex

At Microsoft

They wanted to see if I understood the difference between if and while when checking conditions. Always use while - prevents spurious wakeups and handles multiple consumers.

Also asked about semaphores as alternative solution. Semaphores work but condition variables give more control.

Scroll to Top