【问题标题】:Should I notify while holding the lock on a condition or after releasing it?我应该在持有某个条件的锁时还是在释放它之后通知?
【发布时间】:2016-09-20 10:12:03
【问题描述】:

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

通知线程不需要在同一个互斥体上持有锁 作为等待线程持有的线程;事实上这样做是一个 悲观化,因为被通知的线程会立即阻塞 再次等待通知线程释放锁。

那建议做这样的事情:

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

【问题讨论】:

    标签: python multithreading python-multithreading


    【解决方案1】:

    不要阅读 C++ 文档来了解 Python API。每the actual Python docs

    如果调用此方法时调用线程尚未获得锁,则会引发RuntimeError

    Python 明确要求在notifying 时持有锁。

    【讨论】:

    • 哦,我错过了。那么消费者不会立即阻止吗?
    • @NeilG:是的,但这无论如何都会发生(大多数时候),他们甚至需要the GIL 才能再次开始执行,而notify 不会释放 GIL。调用notify 的线程将在释放之前完成其时间片(假设他们在with 块的末尾为Condition 调用notify,通常会给它时间释放Condition) GIL,此时notify-ed 线程唤醒,并希望同时获得 GIL 和 Condition。如果其他线程先获取 GIL,可能需要一些时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2020-09-10
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多