← Lessons

quiz vs the machine

Gold1350

Concurrency

The Multithreaded FizzBuzz

Four threads cooperate to print fizz buzz fizzbuzz and numbers strictly in order.

4 min read · core · beat Gold to climb

The challenge

Four threads share a counter from one to n. One prints fizz for multiples of three, one prints buzz for multiples of five, one prints fizzbuzz for multiples of fifteen, and one prints the number otherwise. Each value must be printed exactly once in increasing order.

Why coordination is needed

The threads must take turns based on the current number. Only the thread whose condition matches the current value may print, then it advances and wakes the others. This is a conditional handoff rather than a free for all.

A clean solution

Hold the shared counter under a mutex with a condition variable. Each thread loops:

  • Wait until the current number both is within range and matches its rule.
  • Print its token.
  • Increment the counter and notify all waiting threads.

Because every thread rechecks the predicate after waking, only the correct thread prints for each value. Notifying all threads avoids a lost wakeup where the right thread sleeps through its turn.

Key idea

Multithreaded FizzBuzz is a turn based handoff where each thread waits for the matching number, prints once, advances the counter, and notifies the rest.

Check yourself

Answer to earn rating on the learn ladder.

1. How do the four threads stay in order?

2. Why notify all threads after incrementing?