Interleaved Dual-Thread Sequencer
Data Structure DesignModel answerLast updated
Coordinate two concurrent threads to output consecutive integers from 1 to n in strictly alternating parity order.
Design and implement a thread synchronization class named AlternatingPrinter that takes an integer n upon initialization. The class coordinates two separate threads: one responsible for processing odd numbers and the other for processing even numbers. Together, they must output numbers from 1 to n in strict sequential order (1, 2, 3, ..., n).
The class must expose two methods:
printOdd(printNumber): Executed by the odd-number thread. It invokes the provided functionprintNumber(val)for each odd integer.printEven(printNumber): Executed by the even-number thread. It invokes the provided functionprintNumber(val)for each even integer.
Constraints
- $1 \le n \le 1000$
- Output must strictly follow the incremental order: $1, 2, 3, \ldots, n$.
- No thread should block indefinitely (deadlock) after all numbers up to $n$ have been printed.
Example
For n = 5:
- Odd thread prints:
1,3,5 - Even thread prints:
2,4 - Combined order of calls to
printNumber:1,2,3,4,5
Class Signature
import threading
class AlternatingPrinter:
def __init__(self, n: int):
self.n = n
# Initialize thread synchronization constructs here
def printOdd(self, printNumber: callable) -> None:
pass
def printEven(self, printNumber: callable) -> None:
pass
Hints
Hint 1
Use a single shared counter variable to keep track of the next number that needs to be printed.
Hint 2
Ensure both threads handle the termination condition (`counter > n`). When one thread finishes printing the final value, it must wake up the other thread so it does not remain suspended forever.
Hint 3
Condition variables or semaphores can be used to signal between threads when it is their turn to execute.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach 1: Shared Counter with Condition Variable
The standard and robust way to coordinate threads checking a shared predicate is using a mutex/lock paired with a Condition Variable (guarded wait).
Key Components
- Shared State: A single integer counter
self.currentinitialized to1. - Synchronization Primitive:
threading.Condition(), which wraps a reentrant lock. - Turn Evaluation:
- The odd thread acts when
self.current % 2 == 1. - The even thread acts when
self.current % 2 == 0.
- The odd thread acts when
- Exit Strategy:
- Both threads loop until
self.current > n. - Before exiting, a thread must notify all waiting threads to ensure the other worker thread wakes up, observes that
self.current > n, and gracefully finishes its execution.
- Both threads loop until
Python Implementation
import threading
class AlternatingPrinter:
def __init__(self, n: int):
self.n = n
self.current = 1
self.cond = threading.Condition()
def printOdd(self, printNumber: callable) -> None:
self._run(target_parity=1, printNumber=printNumber)
def printEven(self, printNumber: callable) -> None:
self._run(target_parity=0, printNumber=printNumber)
def _run(self, target_parity: int, printNumber: callable) -> None:
while True:
with self.cond:
# Wait until it is either this thread's turn or printing is complete
self.cond.wait_for(
lambda: self.current > self.n or self.current % 2 == target_parity
)
# Check if execution finished
if self.current > self.n:
# Wake up any dormant threads so they can also terminate
self.cond.notify_all()
return
# Perform the print action and advance the counter
printNumber(self.current)
self.current += 1
# Signal the other thread that the counter state changed
self.cond.notify_all()
Approach 2: Handshake via Semaphores
An alternative approach uses two binary semaphores (or event flags) to pass execution control back and forth like a baton.
odd_seminitialized to1(odd starts first).even_seminitialized to0.
Each thread knows precisely which numbers it is responsible for producing without relying on a shared state counter during execution.
import threading
class AlternatingPrinterSemaphores:
def __init__(self, n: int):
self.n = n
self.odd_sem = threading.Semaphore(1)
self.even_sem = threading.Semaphore(0)
def printOdd(self, printNumber: callable) -> None:
for val in range(1, self.n + 1, 2):
self.odd_sem.acquire()
printNumber(val)
self.even_sem.release()
def printEven(self, printNumber: callable) -> None:
for val in range(2, self.n + 1, 2):
self.even_sem.acquire()
printNumber(val)
self.odd_sem.release()
Complexity Analysis
- Time Complexity: $\mathcal{O}(n)$. Every number from $1$ to $n$ undergoes a constant number of lock acquisitions, predicate evaluations, and thread awakenings.
- Space Complexity: $\mathcal{O}(1)$. Memory usage relies on a fixed set of synchronization primitives and variables, independent of $n$.
Key Edge Cases & Common Pitfalls
-
Unterminated Threads (Deadlock on Completion):
- Issue: If $n = 5$, the odd thread prints $5$ and updates
currentto $6$. If it exits without notifying the even thread, the even thread remains stuck waiting oncond.wait_for(...). - Fix: Always invoke
notify_all()when exiting the loop so waiting threads can evaluate the terminal predicate (self.current > self.n) and terminate properly.
- Issue: If $n = 5$, the odd thread prints $5$ and updates
-
Spurious Wakeups:
- Issue: Threads can wake up without a signal due to OS-level signaling behavior.
- Fix: Avoid using plain
ifchecks. Wrap wait logic inside awhileloop or useCondition.wait_for(predicate).
-
Thread Start Order Independence:
- The even thread might start before the odd thread. Using condition predicates or initialized semaphores ensures that if the even thread runs first, it safely blocks until the odd thread processes
1.
- The even thread might start before the odd thread. Using condition predicates or initialized semaphores ensures that if the even thread runs first, it safely blocks until the odd thread processes