Вот мой пример, но если вы посмотрите на вывод
#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()
output:
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