主要用于生產者,消費者模型
class Dispatcher:
def __init__(self):
self.data = None
self.event = threading.Event()
def produce(self, total):
for _ in range(total):
data = random.randint(0,100)
logging.info(data)
self.data = data
self.event.wait(1)
self.event.set()
def consume(self):
while not self.event.is_set():
data = self.data
logging.info("recieved {}".format(data))
self.data = None
self.event.wait(0.5)
d = Dispatcher()
p = threading.Thread(target=d.produce, args=(10, ), name='producer')
c= threading.Thread(target=d.consume, name='consumer')
c.start()
p.start()
# 消費者主動去消費,需要主動去查看下生產者有沒有生產數據
生產者生產出數據,通知消費者來消費
class Dispatcher:
def __init__(self):
self.data = None
self.event = threading.Event()
self.cond = threading.Condition()
def produce(self, total):
for _ in range(total):
data = random.randint(0,100)
with self.cond:
logging.info(data)
self.data = data
self.cond.notify(2)
# self.cond.notify_all()
self.event.wait(1)
self.event.set()
def consume(self):
while not self.event.is_set():
with self.cond:
self.cond.wait()
data = self.data
logging.info("recieved {}".format(data))
self.data = None
self.event.wait(0.5)
d = Dispatcher()
p = threading.Thread(target=d.produce, args=(10, ), name='producer')
# c= threading.Thread(target=d.consume, name='consumer')
# c.start()
for i in range(5):
c = threading.Thread(target=d.consume, name="consumer-{}".format(i))
c.start()
p.start()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。