python线程-如何“condition.wait”和“condition.notifyAll”

2024-05-19 17:07:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

    ....

    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)

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

谢谢, 李


Tags: the代码selflocktime消费者sleepprint
2条回答

我认为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.

当然,任何时候都只能有一个线程拥有锁:这就是首先拥有锁的目的!

因此,low,notifyAll将所有等待的线程置于准备运行状态,本质上所有线程都在等待再次获取锁以便继续:一旦通知程序释放锁,等待获取该锁的线程中的一个将获得该锁(其他线程,如果有的话,继续等待再次释放该锁,因此在任何给定时间只有一个线程拥有锁)。

钥匙在等待的循环中:

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

cond.wait()是这样实现的(仅示例):

def wait():
    cond.release()
    wait for notify
    cond.aquire()

因此,一次只有一个消费者退出“wait”功能,这要归功于锁。第一个退出wait函数的使用者检测到itemq.isEmpty()==false并继续使用该项。然后重新进入等待功能并释放锁。

第二个使用者退出,再次检测到itemq.isEmpty()==true,然后立即重新输入wait()。

相关问题 更多 >