Neil G Neil G - 2 months ago 12
Python Question

Should I notify while holding the lock on a condition or after releasing it?

The Python

documentation lists the following example of a producer:

from threading import Condition
cv = Condition()

# Produce one item
with cv:
make_an_item_available()
cv.notify()


I had to review threading and I looked at the C++ documentation, which states:


The notifying thread does not need to hold the lock on the same mutex
as the one held by the waiting thread(s); in fact doing so is a
pessimization, since the notified thread would immediately block
again, waiting for the notifying thread to release the lock.


That would suggest doing something like this:

# Produce one item
with cv:
make_an_item_available()
cv.notify()

Answer

Don't read C++ documentation to understand Python APIs. Per the actual Python docs:

If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

Python explicitly requires that the lock be held while notifying.