Katkat

Coordinate Three Threads to Print an Ordered Sequence

ArizeSoftware Engineer · Technical Screen

Last updated

This problem tests knowledge of multi-threaded synchronization, specifically the use of condition variables and mutexes to enforce strict ordering among three distinct threads.

Problem Statement

Suppose you are given an integer n and a class SequencePrinter with three methods: printZero(), printEven(), and printOdd(). Design a program that coordinates three threads to print the sequence 01020304... up to n.

Thread Responsibilities:

  1. ZeroThread: Prints 0 and must execute after every other number, appearing between every pair of non-zero numbers.
  2. OddThread: Prints odd numbers in increasing order (1, 3, 5, ...).
  3. EvenThread: Prints even numbers in increasing order (2, 4, 6, ...).

Requirements:

  • The output should be a continuous stream like "0102030405".
  • Use synchronization primitives (e.g., Lock, ConditionVariable, or Semaphore) to ensure correct order.
  • You must provide the implementation for the SequencePrinter class.

Example:

Input: n = 5 Output: 0102030405

Input: n = 2 Output: 0102

Constraints:

  • 1 <= n <= 1000
  • The threads are spawned and managed externally; your logic should handle blocking and signaling correctly.
class SequencePrinter:
    def __init__(self, n):
        self.n = n

    def printZero(self):
        # Logic to print 0
        pass

    def printOdd(self):
        # Logic to print odd numbers
        pass

    def printEven(self):
        # Logic to print even numbers
        pass

Hints

Hint 1

Use a shared state variable (like a counter or a flag) to track which number is next and whether the ZeroThread needs to run.

Hint 2

Utilize a condition variable to block threads while waiting for their specific turn, ensuring you handle spurious wakeups with a while-loop condition.

Hint 3

The ZeroThread should signal the OddThread when it prints 0 followed by an odd index, and the EvenThread when it prints 0 followed by an even index.

Follow-up questions

  • How would you modify your solution if the number of threads was increased to support multiple even/odd workers?
  • Explain why a simple boolean flag or a volatile variable is insufficient for this problem compared to using condition variables.
  • What are the performance implications of having a large number of context switches in this implementation?