KatInterview

Interleaved Dual-Thread Sequencer

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadingsynchronization

Last 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 function printNumber(val) for each odd integer.
  • printEven(printNumber): Executed by the even-number thread. It invokes the provided function printNumber(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.