KatInterview

Thread-Safe Kitchen: Cook-Once, Pickup-Once Order Pipeline

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencycondition-variableblocking-queue

Last updated

Build a thread-safe kitchen where producers place orders, chefs cook them, and customers block until their dish is ready, with no races, deadlocks, or busy-waiting.

Multi-threaded kitchen with blocking pickup

Implement a thread-safe in-memory kitchen. Many threads submit orders, a pool of chef threads cooks them, and many customer threads wait for their own dish and collect it.

Order data

Every order carries:

  • order_id: a unique integer
  • item_name: a string
  • cook_time_ms: a positive integer, the time a chef spends cooking it

Operations

Names and signatures are up to you:

  • placeOrder(order_id, item_name, cook_time_ms) submits an order.
  • startKitchen(num_chefs) launches the background chef threads.
  • pickupOrder(order_id) blocks until that order has been cooked, then returns it to the caller.
  • shutdown() stops all background threads cleanly.

Guarantees your design must provide

  1. An order is never handed over before it has finished cooking.
  2. Each order is cooked exactly once and collected at most once.
  3. No deadlocks, and no busy-waiting or polling loops.
  4. The system stays correct when N orders are placed and picked up concurrently from many threads.

What to cover in your answer

  • Which synchronization primitives you use (locks, condition variables, semaphores, blocking queues) and why.
  • The data structures and state model used to track each order.
  • How you avoid race conditions and keep the service reasonably fair.
  • How shutdown behaves and which edge cases you handle.

Assume a single process with shared memory. No networking is needed.

Hints

Hint 1

Separate two concerns: distributing cooking work to chefs, and letting customers wait for a specific order. Different primitives suit each.

Hint 2

A FIFO blocking queue of order IDs hands each item to exactly one consumer, which gives cook-once for free. Model each order's lifecycle as a small state machine, and do the check-and-transition for pickup inside one critical section.

Hint 3

Never sleep or block on the queue while holding the shared lock. Wait on a condition in a `while` loop, think about pickup arriving before placement, and use a sentinel per chef that is enqueued after all accepted orders so shutdown drains cleanly.