Search⌘ K
AI Features

Fizz Buzz Problem

Explore how to implement a multithreaded Fizz Buzz solution in Ruby using Mutex and Condition Variables. Understand thread synchronization and conditional printing for numbers divisible by 3, 5, and both.

We'll cover the following...

Problem

FizzBuzz is a common interview problem in which a program prints a number series from 1 to n such that for every number that is a multiple of 3 it prints "fizz", for every number that is a multiple of 5 it prints "buzz" and for every number that is a multiple of both 3 and 5 it prints "fizzbuzz". We will be creating a multi-threaded solution for this problem.

Suppose we have four threads t1, t2, t3 and t4. Thread t1 checks if the number is divisible by 3 and prints fizz. Thread t2 checks if the number is divisible by 5 and prints buzz. Thread t3 checks if the number is divisible by both 3 and 5 and prints fizzbuzz. Thread t4 prints numbers that are not divisible by 3 or 5. The workflow of the program is shown below:

The code for the class is as follows:

class MultithreadedFizzBuzz {
    
    def initialize(n) 
        @n = n   
    end
 
    def fizz
        puts "fizz"
    end
 
    def buzz 
        puts "buzz"
    end
 
    def fizzbuzz
        puts "fizzbuzz"
    end
 
    def Number() 
        puts "#{@num}"
    end
}

For an input integer n, the program should output a string ...