Neil G
Neil G

Reputation: 33242

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

The Python threading 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()

Upvotes: 0

Views: 306

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155507

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.

Upvotes: 2

Related Questions