~/problems / Coordination / Condition variable

Interleave zeros, odds and evens

medium ~20 min

Three threads share one ZeroEvenOdd(n) object; each calls one method once, passing a function print_number(x):

class ZeroEvenOdd:
    def __init__(self, n: int): ...
    def zero(self, print_number) -> None: ...  # prints only 0s
    def even(self, print_number) -> None: ...  # prints only even numbers 2, 4, ...
    def odd(self, print_number) -> None: ...   # prints only odd numbers 1, 3, ...

Together they must print 0 1 0 2 0 3 ... 0 n: a zero before each of 1..n, 2n numbers in total.

n = 3  ->  0 1 0 2 0 3
n = 1  ->  0 1          (the even thread prints nothing but must still return)

The threads start in any order and all three must return.

Each method may only print its own kind of number (zero never prints 1, and so on). Any threading primitives are fine; no sleeping or busy-waiting.

Show hint

Number the 2n prints as steps 0..2n-1 and keep the current step in shared state guarded by one threading.Condition. Each thread knows in advance which steps are its own, so it can loop over them and wait for each one's turn.

Topic: Condition variable. wait_for(predicate) + notify_all; always include a termination case.

0:00
Ctrl ' run · Ctrl ↵ submit
esc