Three-Thread Ordered Printer with Condition Variables
System DesignModel answerLast 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:
- The zero thread emits only
0, exactlyntimes, and each0acts as a separator: every non-zero value is immediately preceded by a0and immediately followed by a0(the last printed character fornisn). - The odd thread emits
1, 3, 5, …in that order, skipping values greater thann. - The even thread emits
2, 4, 6, …in that order, skipping values greater thann. - 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→0102030405n = 2→0102n = 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The output is a single strictly serial string, so the concurrency problem is really a baton-passing problem: at any moment at most one thread should be permitted to print, and after printing it hands the baton to exactly one successor. Trying to coordinate three independent counters leads to races; a shared "whose turn" state is far easier to reason about.
Two pieces of state under one mutex are enough:
zero_turn—Truewhen the next character must be a0.cur— the next non-zero number that may be printed, starting at1.
From these the rule for each thread is mechanical:
| Thread | May print when | After printing |
|---|---|---|
| zero | zero_turn | zero_turn = False |
number thread printing i | not zero_turn and cur == i | cur += 1; zero_turn = True |
Since only the odd thread ever matches an odd cur and only the even thread matches an even cur, at most one thread's predicate is ever satisfiable, which forces the interleaving.
Wrap a threading.Condition (a mutex plus a wait/notify pair) around this state. Each thread loops over the items it owns — the zero thread runs n iterations, the odd/even threads iterate range(start, n+1, 2) — waits while its predicate is false, prints, updates the state, and calls notify_all(). Because every thread knows its own iteration count, no separate "done" flag is needed: once cur passes n all loops have finished and no thread is left blocked.
Why it is correct
- Mutual exclusion: all reads and writes of
zero_turnandcurhappen while holding the condition's lock, so no thread observes a partially updated state. - Exactly one enabled thread: if
zero_turnis true only the zero thread's predicate holds; otherwise only the thread whose owniequalscurholds, andcurhas a single parity. - No lost wakeups:
wait()atomically releases the lock and sleeps, and the predicate is re-checked under the lock after every wakeup, so a state change can never slip between the check and the sleep. - Progress and termination: each print enables exactly one thread and calls
notify_all();curadvances monotonically from1ton+1, so all bounded loops finish.
import threading
class SequencePrinter:
def __init__(self, n):
self.n = n
self._cv = threading.Condition()
self._zero_turn = True # next char must be '0'
self._cur = 1 # next non-zero value to print
@staticmethod
def _emit(x):
print(x, end="", flush=True)
def printZero(self):
for _ in range(self.n):
with self._cv:
while not self._zero_turn:
self._cv.wait()
self._emit(0)
self._zero_turn = False
self._cv.notify_all()
def _print_numbers(self, start):
for i in range(start, self.n + 1, 2):
with self._cv:
while self._zero_turn or self._cur != i:
self._cv.wait()
self._emit(i)
self._cur += 1
self._zero_turn = True
self._cv.notify_all()
def printOdd(self):
self._print_numbers(1)
def printEven(self):
self._print_numbers(2)
Complexity
There are 2n prints in total, each doing O(1) work plus a constant number of wakeups, so time is O(n) in useful work and O(1) extra space (one lock, one condition, two scalars). notify_all() may wake a thread whose predicate is still false; it simply re-sleeps, which is still O(1) per hand-off.
Alternative: three semaphores
Keep zero = Semaphore(1), odd = Semaphore(0), even = Semaphore(0). The zero thread acquires zero, prints, and releases odd or even depending on the value of cur; each number thread acquires its own semaphore, prints, and releases zero. This wakes exactly the right thread and needs no predicate loop, but it is harder to extend (e.g. to multiple workers) and easy to get wrong when one thread has zero items. The condition-variable version with explicit predicates is the more defensible answer because the invariant is visible in the code.
Common mistakes
- Using
ifinstead ofwhilearoundwait()— spurious or foreign wakeups then produce out-of-order output. - Allowing number threads to decide their own
ifrom a local counter instead of a sharedcur, so two threads can both believe it is their turn. - Forgetting
flush=True(or a shared writer), so buffering reorders characters from different threads. - Adding a termination flag but forgetting to broadcast it, deadlocking idle workers.
- Busy-waiting on a plain boolean: it burns CPU and, in CPython, competes for the GIL with the thread that would flip the flag.
What a strong candidate adds
- States the invariant out loud: exactly one thread is enabled at any moment.
- Notes that start order is irrelevant — a thread that runs early simply blocks on its predicate.
- Checks
n = 1, where the even loop is empty and must return immediately. - Mentions the extension to multiple odd/even workers: workers can no longer pre-assign
i, so they loop claiming the sharedcur, and termination requires adoneflag plus a broadcast; separate conditions per role withnotify()avoid a thundering herd. Adding workers buys no throughput anyway, because the sequence is inherently serial.