Synchronizing Zero, Odd, and Even Worker Threads
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement the SequencePrinter class so that three concurrent worker threads cooperate to emit the interleaved integer stream 0, 1, 0, 2, 0, 3, ..., 0, n for a given upper bound n.
A single SequencePrinter(n, emit=None) instance is shared among three threads created by the caller:
- Zero worker (
printZero): Emits0immediately before every integer from1throughn(emitting0a total ofntimes). - Odd worker (
printOdd): Emits the odd integers1, 3, 5, ...up tonin ascending order, each right after its preceding0. - Even worker (
printEven): Emits the even integers2, 4, 6, ...up tonin ascending order, each right after its preceding0.
Each emitted integer x must be passed to self.emit(x). When emit is None, SequencePrinter uses print_number, which writes x directly to standard output with no separator or trailing newline (so 0, 1, 0, 2 appears as "0102").
class SequencePrinter:
def __init__(self, n, emit=None):
...
def printZero(self):
...
def printOdd(self):
...
def printEven(self):
...
All three methods must coordinate via standard blocking synchronization primitives (threading.Lock, threading.Condition, threading.Semaphore, etc.) so that the output order is deterministic regardless of thread scheduling or start order, and all three threads exit cleanly once n has been emitted.
Examples
Example 1
- Input:
n = 4 - Output:
"01020304"(emitted integers[0, 1, 0, 2, 0, 3, 0, 4]) - Walk-through:
printZero()emits four0s in lockstep withprintOdd()(1, then3) andprintEven()(2, then4), yielding0, 1, 0, 2, 0, 3, 0, 4.
Example 2
- Input:
n = 1 - Output:
"01"(emitted integers[0, 1]) - Walk-through:
printZero()emits a single0,printOdd()emits1, andprintEven()has no even values in1..1, so all three workers finish immediately without hanging.
Example 3
- Input:
n = 7 - Output:
"01020304050607"(emitted integers[0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7]) - Walk-through: Four odd values (
1, 3, 5, 7) and three even values (2, 4, 6) alternate strictly after each0emitted byprintZero().
Constraints
1 <= n <= 1000- The caller starts and joins the three threads in any order.
- Out-of-turn threads must block on synchronization primitives rather than busy-spinning or sleeping for fixed durations.
Step-by-step walkthrough
Restate the problem and exact sequence
Three external threads share a single
SequencePrinter(n)instance and start in any order: - The zero worker callsprintZero()once, - The odd worker callsprintOdd()once, - The even worker callsprintEven()once.As shown by the examples (
n = 1 -> "01",n = 4 -> "01020304",n = 7 -> "01020304050607"), the output has2 * nnumbers in strict lockstep —0immediately before every integer from1up ton:n = 4: 0 1 0 2 0 3 0 4 owner: Z O Z E Z O Z ECounting how many numbers each thread owns gives clean loop bounds right away: -
printZero()emits0exactlyntimes. -printOdd()emits1, 3, 5, ... <= n(range(1, n + 1, 2)). -printEven()emits2, 4, 6, ... <= n(range(2, n + 1, 2)— which is0items whenn = 1!).To keep testing clean while preserving
SequencePrinter(n)'s default stdout behavior,__init__(self, n, emit=None)accepts an optionalemitfunction defaulting toprint(x, end="", flush=True).Why sleeping or busy-waiting fails
Before reaching for synchronization primitives, see why simpler shortcuts break: 1. No synchronization: The OS scheduler runs threads in arbitrary bursts, so the even worker might print
24before the zero worker prints its first0. 2.time.sleep(...)delays: Only guesses how fast another thread will run; any CPU spike violates the order. 3. Busy-waiting (while not my_turn: pass): Two waiting threads burn 100% CPU doing nothing. Worse, in CPython, a spinning thread holds onto the Global Interpreter Lock (GIL) for up to5 ms(sys.getswitchinterval()) before letting the thread that actually needs to run make progress!Instead, out-of-turn threads should sleep at zero CPU cost on a condition variable and be woken up as soon as their turn arrives.
Design the shared state machine and turn predicates
Two tiny state variables completely describe whose turn it is at every moment: -
next_number: which non-zero integer in1 .. ncomes next (starts at1). -zero_turn:Truewhen0must be emitted beforenext_number, andFalseonce that0has been emitted (starts atTrue).From those two variables, each thread's "is it my turn?" rule (its predicate) is unambiguous: - Zero worker can go when
zero_turnisTrue. - Odd worker (on numberk) can go whennot zero_turn and next_number == k. - Even worker (on numberk) can go whennot zero_turn and next_number == k.Step (next_number, zero_turn) Active predicate Emits Next state -------------------------------------------------------------------------------- 1 (1, True) Zero worker 0 (1, False) 2 (1, False) Odd worker (k = 1) 1 (2, True) 3 (2, True) Zero worker 0 (2, False) 4 (2, False) Even worker (k = 2) 2 (3, True) 5 (3, True) Zero worker 0 (3, False) 6 (3, False) Odd worker (k = 3) 3 (4, True) 7 (4, True) Zero worker 0 (4, False) 8 (4, False) Even worker (k = 4) 4 (5, True) -> doneNotice the key invariant: in every reachable state, at most one thread's predicate is
True.Share one mutex across three targeted condition variables
A mutex (
threading.Lock) ensures only one thread reads or updates(next_number, zero_turn)at a time. A condition variable (threading.Condition) adds a sleep queue on top of a mutex: callingcv.wait()atomically releases the mutex and puts the calling thread to sleep, then re-acquires the mutex before returning when woken.Why pass the same
lockinto three separateCondition(lock)instances (zero_cv,odd_cv,even_cv)? - Because all three sharelock, enteringwith self.zero_cv:,with self.odd_cv:, orwith self.even_cv:acquires the exact same mutex, protecting the shared state from races. - Because eachConditionhas its own wait queue, the zero worker can wake onlyodd_cvwhennext_numberis odd and onlyeven_cvwhennext_numberis even, instead of waking both and forcing the wrong one right back to sleep.Always wrap
wait()in awhileloop (while not my_predicate: cv.wait()), never anif, so any spurious wake-up (an OS wake-up with no matchingnotify()) re-checks the state before proceeding.import threading def print_number(x): """Default output: write the number with no separator, like '0102...'.""" print(x, end="", flush=True) class SequencePrinter: def __init__(self, n, emit=None): self.n = n self.emit = emit if emit is not None else print_number # Single mutex guarding next_number, zero_turn, and serialized calls to self.emit(). lock = threading.Lock() # Three condition variables sharing the same lock so each thread sleeps on its own queue # and wake-ups target only the exact thread whose turn comes next. self.zero_cv = threading.Condition(lock) self.odd_cv = threading.Condition(lock) self.even_cv = threading.Condition(lock) # next_number: integer in 1..n+1 indicating which non-zero number comes next. self.next_number = 1 # zero_turn: True when a 0 must be emitted before next_number; False when next_number is due. self.zero_turn = TrueImplement `printZero`, `printOdd`, and `printEven`
Pay close attention to two critical details inside each
withblock: 1. Callself.emit(...)inside the lock BEFORE flippingzero_turn. If a thread flippedzero_turnand released the lock before callingself.emit(0), the woken odd worker could acquire the lock and print1before0reachedstdout! 2. Loop over each thread's exact assigned range.printZeroloopsself.ntimes;_print_numbersloops overrange(first, self.n + 1, 2). In Example 2 (n = 1), the even worker getsrange(2, 2, 2), which is empty, so it returns immediately without ever blocking oneven_cv.def printZero(self): """Emit 0 exactly n times, each one just before the next non-zero number.""" for _ in range(self.n): with self.zero_cv: # Re-check in a while loop to guard against spurious or early wake-ups. while not self.zero_turn: self.zero_cv.wait() # Emit inside the lock BEFORE flipping zero_turn so 0 finishes printing # strictly before the odd/even thread can print next_number. self.emit(0) self.zero_turn = False # Wake only the specific worker responsible for next_number's parity. if self.next_number % 2 == 1: self.odd_cv.notify() else: self.even_cv.notify() def printOdd(self): """Emit 1, 3, 5, ... up to n, each one right after its 0.""" self._print_numbers(1, self.odd_cv) def printEven(self): """Emit 2, 4, 6, ... up to n, each one right after its 0.""" self._print_numbers(2, self.even_cv) def _print_numbers(self, first, my_cv): """Emit first, first + 2, ... up to n, waiting on my_cv for each turn.""" # Iterating over range(first, n + 1, 2) gives this thread its exact count of turns # (and exits immediately when n = 1 and first = 2, preventing deadlock). for k in range(first, self.n + 1, 2): with my_cv: while self.zero_turn or self.next_number != k: my_cv.wait() self.emit(k) self.next_number += 1 self.zero_turn = True self.zero_cv.notify()What if the zero worker finishes round 1 and calls
self.odd_cv.notify()before the odd worker has even started running? No wake-up is lost! When the odd worker later enterswith self.odd_cv:, it seeszero_turn == Falseandnext_number == 1right away, skipsmy_cv.wait(), and prints1.Trace Example 1 (`n = 4`) when the even worker starts first
Initial state: next_number = 1, zero_turn = True 1. Even worker enters (k = 2): acquires lock -> sees zero_turn == True -> calls even_cv.wait() (releases lock & sleeps) 2. Odd worker enters (k = 1): acquires lock -> sees zero_turn == True -> calls odd_cv.wait() (releases lock & sleeps) 3. Zero worker enters (round 0 of 4): acquires lock -> zero_turn is True -> emits 0 -> sets zero_turn = False next_number (1) is odd -> calls odd_cv.notify() -> loops & sleeps on zero_cv.wait() 4. Odd worker wakes (k = 1): emits 1 -> sets next_number = 2, zero_turn = True -> notifies zero_cv -> sleeps for k = 3 5. Zero worker wakes (round 1 of 4): emits 0 -> sets zero_turn = False -> next_number (2) is even -> notifies even_cv -> sleeps 6. Even worker wakes (k = 2): emits 2 -> sets next_number = 3, zero_turn = True -> notifies zero_cv -> sleeps for k = 4 7. Rounds 2 and 3 repeat the exact hand-off: Zero emits 0 -> Odd wakes, emits 3 & exits -> Zero emits 0 & exits -> Even wakes, emits 4 & exits!Emitted stream:
01020304, with all three threads terminating cleanly.Complete solution
import threading def print_number(x): """Default output: write the number with no separator, like '0102...'.""" print(x, end="", flush=True) class SequencePrinter: """Three threads share one SequencePrinter(n) and together emit 0 1 0 2 0 3 ... 0 n. One thread calls printZero(), one calls printOdd() and one calls printEven(), in any start order. Each number is passed to `emit` (print_number by default). """ def __init__(self, n, emit=None): self.n = n self.emit = emit if emit is not None else print_number # Single mutex guarding next_number, zero_turn, and serialized calls to self.emit(). lock = threading.Lock() # Three condition variables sharing the same lock so each thread sleeps on its own queue # and wake-ups target only the exact thread whose turn comes next. self.zero_cv = threading.Condition(lock) self.odd_cv = threading.Condition(lock) self.even_cv = threading.Condition(lock) # next_number: integer in 1..n+1 indicating which non-zero number comes next. self.next_number = 1 # zero_turn: True when a 0 must be emitted before next_number; False when next_number is due. self.zero_turn = True def printZero(self): """Emit 0 exactly n times, each one just before the next non-zero number.""" for _ in range(self.n): with self.zero_cv: # Re-check in a while loop to guard against spurious or early wake-ups. while not self.zero_turn: self.zero_cv.wait() # Emit inside the lock BEFORE flipping zero_turn so 0 finishes printing # strictly before the odd/even thread can print next_number. self.emit(0) self.zero_turn = False # Wake only the specific worker responsible for next_number's parity. if self.next_number % 2 == 1: self.odd_cv.notify() else: self.even_cv.notify() def printOdd(self): """Emit 1, 3, 5, ... up to n, each one right after its 0.""" self._print_numbers(1, self.odd_cv) def printEven(self): """Emit 2, 4, 6, ... up to n, each one right after its 0.""" self._print_numbers(2, self.even_cv) def _print_numbers(self, first, my_cv): """Emit first, first + 2, ... up to n, waiting on my_cv for each turn.""" # Iterating over range(first, n + 1, 2) gives this thread its exact count of turns # (and exits immediately when n = 1 and first = 2, preventing deadlock). for k in range(first, self.n + 1, 2): with my_cv: while self.zero_turn or self.next_number != k: my_cv.wait() self.emit(k) self.next_number += 1 self.zero_turn = True self.zero_cv.notify() if __name__ == "__main__": printer = SequencePrinter(4) threads = [ threading.Thread(target=printer.printZero), threading.Thread(target=printer.printEven), threading.Thread(target=printer.printOdd), ] for t in threads: t.start() for t in threads: t.join() print()✅ Submit now — all tests should pass.
Intuition & how it works
Picture three musicians in a small studio who must play notes in the strict alternating pattern 0, 1, 0, 2, 0, 3, ..., where one musician only plays 0, one only plays odd numbers, and one only plays even numbers. There is one whiteboard on the wall showing (next_number, zero_turn), one room key — a mutex (a mutual-exclusion lock that lets only one thread inspect or change shared state at a time) — and three nap chairs — condition variables (synchronization queues that let a thread release the lock, sleep using zero CPU, and re-acquire the lock when tapped awake). Whoever enters the room checks the whiteboard: if it is not their turn, they sit in their chair and sleep; if it is their turn, they play their note, update the whiteboard, and tap the exact chair of whoever plays next.
Without synchronization, the OS thread scheduler interleaves the three threads unpredictably and scrambles the output (such as 200134). Trying to fix that with time.sleep() breaks whenever one thread lags under CPU load, while busy-waiting (spinning in an empty while loop until a variable changes) wastes CPU cores and, in CPython, hogs the Global Interpreter Lock (GIL) (CPython's internal lock allowing only one thread to execute Python bytecode at a time) for milliseconds per switch.
Walk through Example 1 (n = 4) starting from next_number = 1, zero_turn = True:
1. The zero worker sees zero_turn == True, emits 0, flips zero_turn = False, sees 1 is odd, and wakes odd_cv.
2. The odd worker wakes, sees not zero_turn and next_number == 1, emits 1, sets next_number = 2 and zero_turn = True, and wakes zero_cv.
3. The zero worker wakes, emits 0, flips zero_turn = False, sees 2 is even, and wakes even_cv; the even worker emits 2, advances to (3, True), and wakes zero_cv.
4. Two more hand-off pairs emit 0, 3 (odd worker) and 0, 4 (even worker), producing "01020304".
Complexity
- Time: O(n). Across the entire run,
2 * nnumbers are emitted (nzeros andnintegers1..n). Each emitted number performs oneO(1)lock acquisition, oneO(1)state update, and oneO(1)targetednotify(), resulting in2 * nthread hand-offs. - Space: O(1). Regardless of how large
ngrows,SequencePrinterstores only two scalar variables (next_numberandzero_turn), oneLock, and threeConditionobjects.
Edge cases
n = 1(the even worker has zero numbers to print):range(2, 2, 2)is empty, soprintEven()returns immediately instead of callingwait()and hanging forever.- Arbitrary thread start order (or delayed thread start): If the even worker starts first, it sees
zero_turn == Trueand sleeps oneven_cv. Conversely, if the zero worker callsodd_cv.notify()before the odd worker has even enteredprintOdd(), nothing is lost becauseprintOdd()checksself.zero_turnandself.next_numberbefore callingwait(). - Multi-digit integers (
n >= 10): Each integerkis passed whole toself.emit(k), son = 12ends with...09010011012(0,10,0,11,0,12). - Buffered
stdoutwith no newline:print(x, end="")normally buffers output when no'\n'is written, soprint_numberpassesflush=Trueto make streaming output visible immediately.
Common mistakes
- Using
ifinstead ofwhilearoundcv.wait(): Operating systems permit spurious wake-ups (a sleeping thread waking fromwait()even though its condition was not satisfied), and anynotify_all()design wakes non-matching threads too. Always re-test the predicate in awhileloop. - Creating three
threading.Condition()objects without sharing oneLock: Callingthreading.Condition()with no argument creates three independent locks, meaning two workers can mutatezero_turnandnext_numbersimultaneously in a data race (concurrent unsynchronized access to shared memory where at least one access is a write). - Calling
self.emit(...)outside the lock or after flippingzero_turn: Oncezero_turnflips and the lock is released, the next thread is free to run immediately and can print its number before the previous thread'sprint()finishes! - Checking
while self.next_number <= self.n:dynamically at the top ofprintZero():printZero()can passnext_number <= nwhilenis still waiting to print, go to sleep, wake up afternfinishes, and emit an extra trailing0(2n + 1numbers). Precomputing exact iteration counts (range(self.n)andrange(first, self.n + 1, 2)) avoids off-by-one hangs and extra outputs.
Alternative approaches
- Three semaphores (
threading.Semaphore): A semaphore (a thread-safe counter whoseacquire()decrements/blocks at0and whoserelease()increments/wakes a waiter) solves this cleanly withzero_sem = Semaphore(1),odd_sem = Semaphore(0),even_sem = Semaphore(0):printZeroacquireszero_sem, emits0, and releasesodd_semoreven_sem;printOddandprintEvenacquire their semaphore, emitk, and releasezero_sem. Condition variables with explicit state are easier to extend when multiple workers share a parity pool. - Single
Conditionwithnotify_all(): Slightly shorter setup (oneCondition()instead of three sharing aLock), at the cost of waking both waiting threads on every step so one immediately goes back to sleep.
Follow-up questions
- How would you adapt the design if pools of multiple odd threads and multiple even threads shared the workload? Instead of giving each odd/even worker a fixed
for k in range(...)loop, have every odd worker run awhile Trueloop under the shared lock: wait while(zero_turn or next_number % 2 == 0) and next_number <= n, return immediately oncenext_number > n, and otherwise claimk = self.next_number, emitk, incrementnext_number, setzero_turn = True, and notifyzero_cv. When the final numbernis emitted (next_number == n + 1), callodd_cv.notify_all()andeven_cv.notify_all()(whileprintZerowakes a single worker vianotify()) so every idle worker in both pools wakes up, seesnext_number > n, and exits cleanly without hanging. - Why can't a single boolean flag or a volatile variable replace mutex-backed condition variables here? First, a single boolean only encodes
2states, which cannot distinguish3distinct roles (Zero,Odd,Even). Second, plain flags andvolatilevariables cannot put a waiting thread to sleep in the OS kernel — threads must spin in a tight loop, burning 100% CPU and starving peers of CPU cores (and the GIL in Python). Third, in C and C++volatileexists for memory-mapped hardware I/O and provides zero atomicity or memory-visibility guarantees across threads; even with Javavolatileor C++std::atomic, "read state, emit output, update state" is not atomic across multiple steps without a mutex or compare-and-swap coordination. - How does per-number thread hand-off overhead affect throughput at scale, and how do production pipelines avoid that bottleneck? Strictly serializing output item-by-item forces
2 * ncontext switches (saving one thread's CPU state and scheduling another thread onto a core, typically involving kernelfutexsystem calls and cache invalidations). When each turn only formats a tiny integer, wake-up overhead (~microseconds per hand-off) makes the multi-threaded run roughly50x–100xslower than a single-threaded loop (~nanoseconds per iteration). Production pipelines amortize synchronization by having worker threads process coarse-grained batches independently and pass completed chunks over a bounded queue to a dedicated writer thread.
Follow-up questions
- How would you adapt the design if pools of multiple odd threads and multiple even threads shared the workload?
- Why can't a single boolean flag or a volatile variable replace mutex-backed condition variables here?
- How does per-number thread hand-off overhead affect throughput at scale, and how do production pipelines avoid that bottleneck?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes