Sharing a queue among three threads
Share a queue among three threads A, B, C as per given norms :
- 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.