我应该在持有某个条件的锁时通知还是在释放它之后通知?
Should I notify while holding the lock on a condition or after releasing it?
Python threading
documentation 列出了以下生产者示例:
from threading import Condition
cv = Condition()
# Produce one item
with cv:
make_an_item_available()
cv.notify()
我不得不复习线程并查看了 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.
建议这样做:
# Produce one item
with cv:
make_an_item_available()
cv.notify()
不要阅读 C++ 文档来理解 Python API。每 the actual Python docs:
If the calling thread has not acquired the lock when this method is called, a RuntimeError
is raised.
Python 明确要求在 notify
ing 时保持锁定。
Python threading
documentation 列出了以下生产者示例:
from threading import Condition
cv = Condition()
# Produce one item
with cv:
make_an_item_available()
cv.notify()
我不得不复习线程并查看了 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.
建议这样做:
# Produce one item
with cv:
make_an_item_available()
cv.notify()
不要阅读 C++ 文档来理解 Python API。每 the actual Python docs:
If the calling thread has not acquired the lock when this method is called, a
RuntimeError
is raised.
Python 明确要求在 notify
ing 时保持锁定。