Standard condition variables have the following guarantees:
* if there are any waiters then signal()/notify() will awaken at least one of them;
* if there are any waiters then broadcast()/notify_all() will awaken all of them.
The implementation in condvar.h does not have these guarantees since a future waiter (possibly the signalling thread) may steal the signal intended for a current waiter.
In many cases this does not matter, but in some it can cause a deadlock. For instance, consider
from threading import Condition, Thread
import time
def set_to_value(value, cond, state):
while 1:
with cond:
while state.value == value:
cond.wait()
state.value = value
print("set_to_value(%s)" % value)
cond.notify_all()
class state:
value = False
c = Condition()
for i in (0, 1):
t = Thread(target=set_to_value, args=(i, c, state))
t.daemon = True
t.start()
time.sleep(5)
This *should* make state.value bounce back and forth between 0 and 1 continually for five seconds.
But using a condition variable implemented like in condvar.h this program is liable to deadlock because the signalling thread steals the signal intended for the other thread.
I think a note about this should be added to condvar.h. |