Magicsheet logo

Fizz Buzz Multithreaded

Medium
12.5%
Updated 8/1/2025

Asked by 3 Companies

Fizz Buzz Multithreaded

1. What is this problem about?

The Fizz Buzz Multithreaded interview question takes the classic logic problem into the world of concurrency. You have four threads that share a single FizzBuzz object.

  • Thread A calls fizz() (prints "fizz" if divisible by 3).
  • Thread B calls buzz() (prints "buzz" if divisible by 5).
  • Thread C calls fizzbuzz() (prints "fizzbuzz" if divisible by 15).
  • Thread D calls number() (prints the number if none of the above). The threads must synchronize so that the output is printed in the correct order from 1 to nn.

2. Why is this asked in interviews?

Companies like Meta and Amazon use the Fizz Buzz Multithreaded coding problem to evaluate a candidate's knowledge of Concurrency primitives. It tests your ability to use Mutexes, Semaphores, or Condition Variables to coordinate different execution paths. It is a test of avoiding race conditions and deadlocks in a coordinated output stream.

3. Algorithmic pattern used

This problem uses the Condition Variable / Barrier pattern.

  1. Shared State: Keep a shared counter curr initialized to 1.
  2. Synchronization: Each thread runs a loop. Inside the loop, it waits on a condition: "Is it my turn to print the current number?"
  3. Signaling:
    • Thread A checks if curr % 3 == 0 and curr % 5 != 0.
    • After a thread prints, it increments curr and signals (notifies) all other threads to check the new value.
  4. Termination: All threads must stop when curr > n.

4. Example explanation

n=3n = 3.

  1. curr = 1. Thread D (number) sees 1 is not div by 3 or 5. Prints "1", curr = 2. Notifies others.
  2. curr = 2. Thread D sees 2 is not div by 3 or 5. Prints "2", curr = 3. Notifies others.
  3. curr = 3. Thread A (fizz) sees 3 is div by 3. Prints "fizz", curr = 4. Notifies others.
  4. Loop ends.

5. Common mistakes candidates make

  • Busy Waiting: Using a while(true) loop without wait() or sleep(), which consumes 100% CPU.
  • Deadlock: Failing to signal other threads after printing, leaving them blocked forever.
  • Spurious Wakeups: Using an if instead of a while when checking the condition before waiting.

6. Interview preparation tip

Master the use of wait() and notifyAll() (or their equivalents in C++ or Python). In a Concurrency interview pattern, always ensure that every path through the code eventually signals the next thread to prevent system hangs.

Similar Questions