Day 6 of 10: I4G10DaysOfCodeChallenge

Day 6 of 10: I4G10DaysOfCodeChallenge

If you are working with multiple threads that contribute to the result of output. An important consideration is how the various threads would communicate, or sync to avoid producing confusing results. Today's Challenge was a lot of that for me (threads talking to each other)

I would like to share my thought process while solving this problem in this article. You can check out the problem statement here to follow along.

Understanding the problem:

We are to modify the given class to output the series [1, 2, "fizz", 4, "buzz", ...] where the ith token (1-indexed) of the series is:

"fizzbuzz" if i is divisible by 3 and 5, "fizz" if i is divisible by 3 and not 5, "buzz" if i is divisible by 5 and not 3, or i if i is not divisible by 3 or 5.

One thing that would come to your mind is running a for loop with range(1, n+1) and print fizz, buzz, fizzbuzz, number conditionally but we only have access to the printFizz(), printBuzz(), printFizzBuzz(), printNumber(x) functions from the Fizz(), Buzz(), FizzBuzz(), Number() methods which are going to be called in four different threads. so we need to modify the various methods to run its independent for loop with range(1, n+1) and only print either fizz, buzz, fizzbuzz or number when the respective conditions are met.

But for us to achieve that series, this for loop needs to occur in sync for all the threads. This is where the threading.Barrier class comes in( a class for synchronizing a fixed number of threads that need to wait for each other).

Each thread calls .wait() on the Barrier after each iteration. They all will remain blocked until the specified number of threads are waiting, and then they are all released at the same time for the next time. This is how we achieve this synchronization to ensure we output the desired series and avoid confusing results.

Below is my code snippet to help you better understand my explanation

day6.PNG