KatInterview

Three-Thread Ordered Printer with Condition Variables

System DesignModel answer
MediumModel answerSystem Designconcurrencysynchronizationcondition-variables

Last updated

Coordinate three threads with a shared lock and condition variable so they emit the interleaved sequence 0,1,0,2,0,3,… up to n.

Context

You are given a class skeleton SequencePrinter(n) exposing three entry points — printZero(), printOdd(), and printEven() — plus an integer n. An external harness (not yours to modify) spawns three threads, one per entry point, in an arbitrary order, and joins them when they finish.

Task

Fill in the three methods so that the three threads cooperatively print, on a single shared output stream, the sequence

0 1 0 2 0 3 0 4 ... 0 n

subject to these rules:

  1. The zero thread emits only 0, exactly n times, and each 0 acts as a separator: every non-zero value is immediately preceded by a 0 and immediately followed by a 0 (the last printed character for n is n).
  2. The odd thread emits 1, 3, 5, … in that order, skipping values greater than n.
  3. The even thread emits 2, 4, 6, … in that order, skipping values greater than n.
  4. The characters must appear in the exact global order above — no two characters may be swapped, duplicated, or dropped, regardless of which thread started first or how the OS schedules them.

Return the completed class (any language; Python shown). The threads themselves must block instead of spinning.

Examples

  • n = 5 → 0102030405
  • n = 2 → 0102
  • n = 1 → 01

Constraints

  • 1 <= n <= 1000
  • You may not reorder, delay-start, or otherwise control the harness threads; your logic alone must enforce ordering.
  • Spurious wakeups are possible.
  • The program must terminate cleanly with every thread joined — no deadlock, even when a thread has zero items to print.

Hints

Hint 1

The output is fully serial, so at any instant exactly one thread should be allowed to run — model the problem as a baton being passed, not as three independent counters.

Hint 2

Keep two small pieces of shared state: a flag saying whose turn it is (the zero thread or a number thread) and the next number to be printed. Every thread waits on a predicate built from those two values.

Hint 3

Guard every wait with a `while` loop on the predicate, not a single `if` — otherwise spurious or misplaced wakeups will let two threads print out of order.

Hint 4

Each thread knows its own print count in advance (`n` zeros; the odd/even values up to `n`), so no separate shutdown flag is needed — but verify a thread with zero work exits immediately.