I have a queue with 50 ints in it, and I have 3 threads that want to race at the queue to print the values in it, with a 2 second delay before trying to get the next int.The queue is not thread safe, and the semaphore protecting is is decoupled from the number of items inside the queue(the number of items in the queue are checked by calling .size() for the queue, but the lock is obtained by blocking on the semaphore until its owner unlocks it.I am trying to understand how to prevent the three threads from accessing the queue at the same time, but at the same time not trying to access the queue if the queue is empty. If the queue is empty, but unlocked, i will have a bunch of threads locking the queue, checking its size, and unlocking it, until something is added to the queue. This seems silly and wasteful; Is there a solution to this?
Preventing multiple threads from racing on a queue while not wastefully polling its size
data structures;concurrency;queues