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) |
1 <= n <= 1000. For n = 7 the calls must come out as 1, 2, fizz, 4, buzz, fizz, 7:
import threading
fb = FizzBuzz(7)
out = []
threads = [
threading.Thread(target=fb.fizz, args=(lambda: out.append("fizz"),)),
threading.Thread(target=fb.buzz, args=(lambda: out.append("buzz"),)),
threading.Thread(target=fb.fizzbuzz, args=(lambda: out.append("fizzbuzz"),)),
threading.Thread(target=fb.number, args=(out.append,)),
]
for t in threads:
t.start()
for t in threads:
t.join()
out # [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.