- 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.
- 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
- Reversing a Queue using another Queue
- Queue in Python
- Reversing a Queue
- Queue using Stacks
- Priority Queue in Python
- Applications of Priority Queue
- Reversing the first K elements of a Queue
- Queue Interface In Java
- Priority Queue | Set 1 (Introduction)
- Sort the Queue using Recursion
- Reversing a queue using recursion
- Reverse a path in BST using queue
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.