Fizz Buzz Multithreaded in C++

Samuel AdesolaSamuel Adesola
2 min read

Overview

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution

Thought Process

The problem related to this task can be approached using the concept of multithreading and concurrency in C++. Making use of the opportunity of parallel programming. To illustrate my thought process on this task, let us assume we have four functions, A, B, C, and D, and the task is to sequentially call each of these functions, using the promise or mutex keyword in C++, any required function can be held while the other is ongoing. First, some variables were declared to hold different sequences, and most importantly a variable called myturn and condition variable check was declared to control when a function is to be called. This variable myturn will be set to 0, 2, 1, or 3 when the conditions stated for each thread are satisfied which is divisible and/or not divisible by 3 and 5.

if(i%3 != 0 and i%5 != 0) {
                turn = 0;
            }
            else if(i%5 == 0 and i%3 != 0) {
                turn = 2;
            }
            else if(i%5 == 0 and i%3 == 0) {
                turn = 3;
            }
            check.notify_all();

The code snippet above was repeated for all the threads. If a particular condition is not satisfied, the program will wait and whenever our condition has been satisfied, the iterator variable will be incremented and the function will be executed.

Conclusion

Multithreading is an important concept in computer architecture and low-level programming and it finds application in many solutions that can be solved using programming. It finds application in the concept of state machine and parallelism. This task as well as other tasks has helped in learning more about lots of programming concepts especially those in c++.

0
Subscribe to my newsletter

Read articles from Samuel Adesola directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Samuel Adesola
Samuel Adesola