~/problems / Coordination / Condition variable

FizzBuzz across four threads

medium ~20 min

Four threads share one FizzBuzz(n) object and each calls exactly one of its methods, once. Between them they must produce the FizzBuzz sequence for 1..n, in order:

method responsible for i when what it calls
fizz(print_fizz) i divisible by 3 but not 5 print_fizz()
buzz(print_buzz) i divisible by 5 but not 3 print_buzz()
fizzbuzz(print_fizzbuzz) i divisible by 15 print_fizzbuzz()
number(print_number) everything else print_number(i)

For n = 7 the calls must come out as: 1, 2, fizz, 4, buzz, fizz, 7.

The threads can start in any order, and all four must return once i passes n, including a thread that never gets a turn (for n = 2, fizz, buzz and fizzbuzz print nothing but must still exit).

Each method may only use its own print function: number must not print "fizz" for another thread. No sleeping or busy-waiting.

Show hint

Keep one shared counter guarded by a single threading.Condition. Each method loops, waiting until the counter is one of its numbers; make sure the wait can also end once the counter is past n, or threads that never get a turn will hang.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc