gpt4 book ai didi

python 线程 - "condition.wait"和 "condition.notifyAll"是如何工作的

转载 作者:行者123 更新时间:2023-11-28 16:53:41 26 4
gpt4 key购买 nike

我有以下“消费者”代码:

    ....

while 1:

time.sleep(self.sleeptime)

cond.acquire() #acquire the lock
print currentThread(), "lock acquired"

while itemq.isEmpty():
cond.wait()

itemq.consume()
print currentThread(),"Consumed One Item"
cond.release()

以及以下生产者代码:

....     
while 1 :


cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
print currentThread(),"Produced One Item"
itemq.produce()
cond.notifyAll()
cond.release()

time.sleep(self.sleeptime)

我正在与 1 个生产者和 2 个消费者一起运行该程序。我不知道会得到什么结果。生产者调用“notifyAll()”,所以我希望两个消费者都能从他们的“等待”中醒来。我看到确实两个消费者都获得了锁,但实际上只有第一个获得锁的人才能消费该元素。有人可以告诉我“等待”命令是如何工作的吗?如果两个线程都获得“notifyAll”,怎么只有一个线程可以消费?

谢谢,李

最佳答案

我认为the docs非常清楚:

The wait() method releases the lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition variable in another thread. Once awakened, it re-acquires the lock and returns. It is also possible to specify a timeout.

:

Note: the notify() and notifyAll() methods don’t release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notifyAll() finally relinquishes ownership of the lock.ownership of the lock.

当然,任何时候都只有一个线程可以拥有锁:毕竟,这首先是拥有锁的核心目的!

所以,IOW,notifyAll 将所有等待线程置于准备运行状态,本质上所有线程都在等待再次获取锁以便它们可以继续:一旦通知程序释放锁,一个等待获取该锁的线程确实获取了它(其他线程,如果有的话,继续等待锁被再次释放,当然,这样在任何给定时间只有一个线程拥有锁) .

关于python 线程 - "condition.wait"和 "condition.notifyAll"是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3737755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com