Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a conditional variable "miss" a notify call?

I was wondering if it were possible for a conditional variable to "miss" a notify call. My scenario is as follows.

Given a mutex mu, and a Pred P (!queue.empty())...

Thread A: Persists for the entirety of the program's life span. Holds a conditional variable waiting on mu and P. Upon acquiring mu and verifying the queue is not empty, it will pop an item from the queue.

Thread B: A function that will acquire mu, push to the queue.

Thread C: Same as B.

Thread B and C are spawned simultaneously.

In this scenario B acquires mu first, pushes to the queue, drops mu and calls notify. In between B calling notify and dropping mu, C acquires mu, pushes to the queue, and calls notify. Finally A acquires mu, proceeds to pop an item from the queue and process it. However A only acts on one of the notify calls.

If you are trying to process the items in the queue one by one, this seems to create a pile up.

Is this a situation that can occur? And do we have to be aware of it? For example, within A, pop UNTIL the queue is empty? Or is this handled by the language?

like image 744
hromer Avatar asked Dec 13 '25 17:12

hromer


1 Answers

If you are trying to process the items in the queue one by one, this seems to create a pile up.

Is this a situation that can occur? And do we have to be aware of it? For example, within A, pop UNTIL the queue is empty? Or is this handled by the language?

Yes it is a situation that can occur and you should be aware of it. In your described scenario, the wait could wake once (with two items in the queue), twice (once per item in the queue) or even N times (spurious wakeups with no items in the queue. This is why you always check your predicate after waking and then make sure the predicate is false prior to re-waiting on the condition. Popping until the queue is empty is a reasonable solution.

like image 146
Andy Avatar answered Dec 15 '25 06:12

Andy