- 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.
- Check if a queue can be sorted into another queue using a stack
- Stack and Queue in Python using queue Module
- Print 1 2 3 infinitely using threads in C
- Queue using Stacks
- Reversing a Queue
- Priority Queue in Python
- Queue Interface In Java
- Reverse a path in BST using queue
- Reversing a queue using recursion
- Reversing the first K elements of a Queue
- Applications of Priority Queue
- Priority Queue | Set 1 (Introduction)
- Find the largest multiple of 3 | Set 1 (Using Queue)
- Applications of Queue Data Structure
- Implement a stack using single 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 firstname.lastname@example.org. 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.