I have the following “consumer” code:
....
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()
And the following producer’s code:
....
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)
I’m running the program with 1 producer and 2 consumers.
I don’t know what result to expect. The producer calls “notifyAll()”, so I expect both consumers to wake up from their “wait”. I see that indeed both consumer acquire the lock, but only the first one who acquired the lock actually get to consume the item. Could somebody please tell me how the “wait” command works? If both threads get the “notifyAll”, how is it that only one gets to consume?
Thanks,
Li
The key is in the loop around the wait:
cond.wait() is implemented something like this (example only):
So only one consumer exits the ‘wait’ function at a time thanks to the lock. The first consumer to exit the wait function detects that itemq.isEmpty() == false and goes on to consume the item. They then re-enter the wait function and release the lock.
The second consumer exits, detects that itemq.isEmpty() == true again, and re-enters wait() right away.