这是我的示例,但是如果您查看输出
#condition
import threading
C = threading.Condition()
import time
items = []
def consumer():
while True:
print(" PRE consumer acquire")
C.acquire()
print(" POST consumer acquired")
if len(items) == 0:
print(" consumer waiting")
C.wait()
print("consumed and RELEASED")
C.release()
def producer():
while True:
C.acquire()
print("producer acquired")
print("product created")
items.append(1)
items.append(2)
C.notify() #notify will unblock the wait, and
print("notified")
time.sleep(1)
C.release()
t = threading.Thread(target = consumer)
t2 = threading.Thread(target = consumer)
t3 = threading.Thread(target = producer)
t.start()
t2.start()
t3.start()
输出:
PRE consumer acquire PRE consumer acquire
>>> producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
notified
producer acquired
product created
您可以看到,尽管有两个使用者线程,但生产者线程几乎完全获得了条件。消费者线程似乎被卡在C.acquire()之前,这意味着它们没有获得锁。
我在做什么错了?
谢谢
更新:
按照所罗门的建议,我更改了代码(注释了获取和发布之间的打印语句):
#condition
import threading
C = threading.Condition()
import time
items = []
def consumer():
while True:
#print(" PRE consumer acquire")
#time.sleep(1)
C.acquire()
print(" POST consumer acquired")
if len(items) == 0:
print(" consumer waiting")
C.wait()
print("consumed and RELEASED")
C.release()
def producer():
while True:
#time.sleep(1)
C.acquire()
print("producer acquired")
print("product created")
items.append(1)
C.notify() #notify will unblock the wait, and
#print("notified")
C.release()
输出:
POST consumer acquired
consumer waiting
POST consumer acquired
consumer waiting
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired
product created
producer acquired