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): Emits 0 immediately before every integer from 1 through n (emitting 0 a total of n times).
  • Odd worker (printOdd): Emits the odd integers 1, 3, 5, ... up to n in ascending order, each right after its preceding 0.
  • Even worker (printEven): Emits the even integers 2, 4, 6, ... up to n in ascending order, each right after its preceding 0.

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 four 0s in lockstep with printOdd() (1, then 3) and printEven() (2, then 4), yielding 0, 1, 0, 2, 0, 3, 0, 4.

Example 2

  • Input: n = 1
  • Output: "01" (emitted integers [0, 1])
  • Walk-through: printZero() emits a single 0, printOdd() emits 1, and printEven() has no even values in 1..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 each 0 emitted by printZero().

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

  1. Restate the problem and exact sequence

    Three external threads share a single SequencePrinter(n) instance and start in any order: - The zero worker calls printZero() once, - The odd worker calls printOdd() once, - The even worker calls printEven() once.

    As shown by the examples (n = 1 -> "01", n = 4 -> "01020304", n = 7 -> "01020304050607"), the output has 2 * n numbers in strict lockstep — 0 immediately before every integer from 1 up to n:

    n = 4:   0   1   0   2   0   3   0   4
    owner:   Z   O   Z   E   Z   O   Z   E
    

    Counting how many numbers each thread owns gives clean loop bounds right away: - printZero() emits 0 exactly n times. - printOdd() emits 1, 3, 5, ... <= n (range(1, n + 1, 2)). - printEven() emits 2, 4, 6, ... <= n (range(2, n + 1, 2) — which is 0 items when n = 1!).

    To keep testing clean while preserving SequencePrinter(n)'s default stdout behavior, __init__(self, n, emit=None) accepts an optional emit function defaulting to print(x, end="", flush=True).

  2. 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 24 before the zero worker prints its first 0. 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 to 5 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.

  3. 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 in 1 .. n comes next (starts at 1). - zero_turn: True when 0 must be emitted before next_number, and False once that 0 has been emitted (starts at True).

    From those two variables, each thread's "is it my turn?" rule (its predicate) is unambiguous: - Zero worker can go when zero_turn is True. - Odd worker (on number k) can go when not zero_turn and next_number == k. - Even worker (on number k) can go when not 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) -> done
    

    Notice the key invariant: in every reachable state, at most one thread's predicate is True.

  4. 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: calling cv.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 lock into three separate Condition(lock) instances (zero_cv, odd_cv, even_cv)? - Because all three share lock, entering with self.zero_cv:, with self.odd_cv:, or with self.even_cv: acquires the exact same mutex, protecting the shared state from races. - Because each Condition has its own wait queue, the zero worker can wake only odd_cv when next_number is odd and only even_cv when next_number is even, instead of waking both and forcing the wrong one right back to sleep.

    Always wrap wait() in a while loop (while not my_predicate: cv.wait()), never an if, so any spurious wake-up (an OS wake-up with no matching notify()) 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 = True
    
  5. Implement `printZero`, `printOdd`, and `printEven`

    Pay close attention to two critical details inside each with block: 1. Call self.emit(...) inside the lock BEFORE flipping zero_turn. If a thread flipped zero_turn and released the lock before calling self.emit(0), the woken odd worker could acquire the lock and print 1 before 0 reached stdout! 2. Loop over each thread's exact assigned range. printZero loops self.n times; _print_numbers loops over range(first, self.n + 1, 2). In Example 2 (n = 1), the even worker gets range(2, 2, 2), which is empty, so it returns immediately without ever blocking on even_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 enters with self.odd_cv:, it sees zero_turn == False and next_number == 1 right away, skips my_cv.wait(), and prints 1.

  6. 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.

  7. 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 * n numbers are emitted (n zeros and n integers 1..n). Each emitted number performs one O(1) lock acquisition, one O(1) state update, and one O(1) targeted notify(), resulting in 2 * n thread hand-offs.
  • Space: O(1). Regardless of how large n grows, SequencePrinter stores only two scalar variables (next_number and zero_turn), one Lock, and three Condition objects.

Edge cases

  • n = 1 (the even worker has zero numbers to print): range(2, 2, 2) is empty, so printEven() returns immediately instead of calling wait() and hanging forever.
  • Arbitrary thread start order (or delayed thread start): If the even worker starts first, it sees zero_turn == True and sleeps on even_cv. Conversely, if the zero worker calls odd_cv.notify() before the odd worker has even entered printOdd(), nothing is lost because printOdd() checks self.zero_turn and self.next_number before calling wait().
  • Multi-digit integers (n >= 10): Each integer k is passed whole to self.emit(k), so n = 12 ends with ...09010011012 (0, 10, 0, 11, 0, 12).
  • Buffered stdout with no newline: print(x, end="") normally buffers output when no '\n' is written, so print_number passes flush=True to make streaming output visible immediately.

Common mistakes

  • Using if instead of while around cv.wait(): Operating systems permit spurious wake-ups (a sleeping thread waking from wait() even though its condition was not satisfied), and any notify_all() design wakes non-matching threads too. Always re-test the predicate in a while loop.
  • Creating three threading.Condition() objects without sharing one Lock: Calling threading.Condition() with no argument creates three independent locks, meaning two workers can mutate zero_turn and next_number simultaneously 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 flipping zero_turn: Once zero_turn flips and the lock is released, the next thread is free to run immediately and can print its number before the previous thread's print() finishes!
  • Checking while self.next_number <= self.n: dynamically at the top of printZero(): printZero() can pass next_number <= n while n is still waiting to print, go to sleep, wake up after n finishes, and emit an extra trailing 0 (2n + 1 numbers). Precomputing exact iteration counts (range(self.n) and range(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 whose acquire() decrements/blocks at 0 and whose release() increments/wakes a waiter) solves this cleanly with zero_sem = Semaphore(1), odd_sem = Semaphore(0), even_sem = Semaphore(0): printZero acquires zero_sem, emits 0, and releases odd_sem or even_sem; printOdd and printEven acquire their semaphore, emit k, and release zero_sem. Condition variables with explicit state are easier to extend when multiple workers share a parity pool.
  • Single Condition with notify_all(): Slightly shorter setup (one Condition() instead of three sharing a Lock), 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 a while True loop under the shared lock: wait while (zero_turn or next_number % 2 == 0) and next_number <= n, return immediately once next_number > n, and otherwise claim k = self.next_number, emit k, increment next_number, set zero_turn = True, and notify zero_cv. When the final number n is emitted (next_number == n + 1), call odd_cv.notify_all() and even_cv.notify_all() (while printZero wakes a single worker via notify()) so every idle worker in both pools wakes up, sees next_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 2 states, which cannot distinguish 3 distinct roles (Zero, Odd, Even). Second, plain flags and volatile variables 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++ volatile exists for memory-mapped hardware I/O and provides zero atomicity or memory-visibility guarantees across threads; even with Java volatile or 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 * n context switches (saving one thread's CPU state and scheduling another thread onto a core, typically involving kernel futex system calls and cache invalidations). When each turn only formats a tiny integer, wake-up overhead (~microseconds per hand-off) makes the multi-threaded run roughly 50x–100x slower 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

Similar questions

More Arize interview questions

All 1 Arize questions →