溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

threading Condition方法

發(fā)布時(shí)間:2020-07-26 15:38:34 來源:網(wǎng)絡(luò) 閱讀:490 作者:windcharger 欄目:編程語言

主要用于生產(chǎn)者,消費(fèi)者模型

消費(fèi)者消費(fèi)速度大于生產(chǎn)者生產(chǎn)速度例子

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ù)

使用Condition改換成通知機(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()
向AI問一下細(xì)節(jié)

免責(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)容。

AI