您好,登錄后才能下訂單哦!
主要用于生產(chǎn)者,消費(fèi)者模型
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()
# 消費(fèi)者主動去消費(fèi),需要主動去查看下生產(chǎn)者有沒有生產(chǎn)數(shù)據(jù)
生產(chǎn)者生產(chǎn)出數(shù)據(jù),通知消費(fèi)者來消費(fèi)
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()
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。