- Thread A generates random integers and pushes them into a shared queue.
- Threads B and C compete with each other to grab an integer from the queue.
- The threads B and C compute the sum of integers that they have grabbed from the queue.
- Compare the sums as computed by B and C. The greatest is the winner.
Prerequisite :- Multithreading
Approach :- Create a global queue which is shared among all three threads. First create all three threads and call the respective functions associated with them.
- producerFun generates random numbers and push them into queue
- add_B function replicates thread B and consumes the queue for certain numbers.
- add_C function replicates thread C and consumes the queue for certain numbers.
Note :- There is mutex lock in every function to avoid any race condition.
Output: B is in wait.. Produced: 10 Produced: 1 Produced: 6 Produced: 6 Produced: 4 C thread consumed: 10 C thread consumed: 1 C thread consumed: 6 C thread consumed: 6 Produced: 1 Produced: 9 Produced: 9 Produced: 6 C thread consumed: 4 C thread consumed: 1 C thread consumed: 9 C thread consumed: 9 C thread consumed: 6 >> C is in wait.. Produced: 5 C thread consumed: 5 Winner is Thread C
Note : Output will be different everytime code runs.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Stack and Queue in Python using queue Module
- Check if a queue can be sorted into another queue using a stack
- Print 1 2 3 infinitely using threads in C
- C++ File Writer-Reader application using Windows Threads
- Reversing a Queue using another Queue
- Queue in Python
- Queue using Stacks
- Reversing a Queue
- Queue Interface In Java
- Reversing the first K elements of a Queue
- Queue of Pairs in C++ STL with Examples
- Reversing a queue using recursion
- Sort the Queue using Recursion
- Applications of Priority Queue
- Priority Queue in Python
Improved By : Akanksha_Rai