Alternate Odd and Even Numbers with Two Threads
OmnissaSoftware Engineer · OnsiteLast updated
This problem tests knowledge of thread synchronization using locks and condition variables to enforce a specific execution order between two concurrent processes.
Problem Statement
Given an integer n, write a class AlternatingPrinter that coordinates two threads to print numbers from 1 to n in an alternating sequence (odd, even, odd, even, etc.). One thread is responsible for printing only odd numbers, and the other is responsible for printing only even numbers.
Implement the following methods:
printOdd(printNumber): A function that takes a functional interfaceprintNumberand prints odd integers.printEven(printNumber): A function that takes a functional interfaceprintNumberand prints even integers.
Constraints
1 <= n <= 1000- The output must be exactly: 1, 2, 3, 4, 5, ... up to
n.
Example
Input: n = 5
Output: 1, 2, 3, 4, 5
Interface
import threading
class AlternatingPrinter:
def __init__(self, n):
self.n = n
# Initialize synchronization primitives here
def printOdd(self, printNumber):
# Implementation for odd numbers
pass
def printEven(self, printNumber):
# Implementation for even numbers
pass
Hints
Hint 1
Use a single ReentrantLock and a Condition variable to manage the state of the next number to be printed.
Hint 2
Maintain a shared variable to track the current number and use a boolean flag or a parity check to determine which thread should proceed.
Hint 3
Ensure that after a thread prints a number, it notifies the other thread and goes into a waiting state until the parity condition is met again.
Follow-up questions
- How would you modify your solution to support three threads printing numbers in a round-robin fashion (1, 2, 3, 1, 2, 3...)?
- What would happen if the 'printNumber' method threw an exception? How does this affect your lock management?
- Can you implement this using semaphores instead of locks and condition variables?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.