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

use*_*400 5 python multithreading wait conditional-statements

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

    ....

    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()
Run Code Online (Sandbox Code Playgroud)

以及以下生产者代码:

....     
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)
Run Code Online (Sandbox Code Playgroud)

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

谢谢,李

Ant*_*ton 1

关键在于等待的循环:

while itemq.isEmpty():
        cond.wait()
Run Code Online (Sandbox Code Playgroud)

cond.wait() 的实现如下(仅示例):

def wait():
    cond.release()
    wait for notify
    cond.aquire()
Run Code Online (Sandbox Code Playgroud)

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

第二个消费者退出,再次检测到 itemq.isEmpty() == true,并立即重新进入 wait()。