Interview challenge · medium · concurrency, threads, synchronization
Print Odd and Even Numbers with Two Threads
The challenge
Start two threads that print the numbers from 1 to N in order. One thread prints only the odd numbers and the other only the even ones, so they have to take turns: the output must be strictly 1, 2, 3, ... whatever the scheduler does.
Example
N = 6 -> odd 1, even 2, odd 3, even 4, odd 5, even 6Idea: share the next number n, one lock and one condition variable. A thread takes the lock and sleeps on the condition until n has its parity (or the count is over); then it prints n, adds one and wakes the other thread. Waiting in a loop that checks the condition again with the lock held means no wake-up is ever lost, and the last thread to print wakes the other one so that both can exit. In Python, Condition.wait_for is that loop; in C it is the while around pthread_cond_wait.
The solution
# Odd and Even Threads - ayotl.dev
from threading import Condition, Thread
N = 10
n = 1 # next number to print
turn = Condition()
def run(parity):
global n
name = "odd " if parity else "even"
def mine():
return n > N or n % 2 == parity
with turn:
while True:
turn.wait_for(mine) # my turn?
if n > N:
break
print(name, n)
n += 1
turn.notify() # other's turn
ts = [Thread(target=run, args=(p,))
for p in (1, 0)]
for t in ts:
t.start()
for t in ts:
t.join()
$ python3 print_odd_even_with_two_threads.py
odd 1
even 2
odd 3
even 4
odd 5
even 6
odd 7
even 8
odd 9
even 10