What is the producer-consumer problem?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Operating Systems development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

The Producer-Consumer problem (Bounded-Buffer problem) is a classic synchronization problem where producers generate data and put it in a shared buffer, and consumers take data from the buffer. Challenges: buffer has a fixed capacity; producers must wait if buffer is full; consumers must wait if buffer is empty; concurrent access must be synchronized. Solution using semaphores: // Shared: Buffer buffer[N]; Semaphore empty = N; // Available slots Semaphore full = 0; // Filled slots Semaphore mutex = 1; // Buffer access lock int in = 0, out = 0; // Buffer pointers // Producer: while (true) { item = produce(); wait(empty); // Wait for empty slot wait(mutex); // Lock buffer buffer[in] = item; in = (in + 1) % N; signal(mutex); // Unlock signal(full); // Signal consumer } // Consumer: while (true) { wait(full); // Wait for item wait(mutex); // Lock buffer item = buffer[out]; out = (out + 1) % N; signal(mutex); // Unlock signal(empty); // Signal producer consume(item); }. Java BlockingQueue solution: BlockingQueue<Item> queue = new LinkedBlockingQueue<>(10); // Producer: queue.put(item); // Blocks if full // Consumer: Item item = queue.take(); // Blocks if empty. Variations: multiple producers and consumers; different produce/consume rates; different buffer policies (priority, LIFO). Real-world: printer spooler (producers = apps sending print jobs, consumer = printer), web server (producers = incoming requests, consumers = worker threads), pipeline stages.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.