threading Condition方法
admin
2023-07-12 06:24:49
0

主要用于生产者,消费者模型

消费者消费速度大于生产者生产速度例子

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()
# 消费者主动去消费,需要主动去查看下生产者有没有生产数据

使用Condition改换成通知机制

生产者生产出数据,通知消费者来消费

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

相关内容

热门资讯

驻马店非遗“大集”开张 把网络... 顶端新闻记者 王丹/文 李思翰 胡楚昊/图红纸剪出“抵制网络谣言”,糖画写下“不信谣不传谣”……5月...
A股三大指数集体收涨 贵金属涨...   A股三大指数集体收涨 贵金属涨幅居前  【A股三大指数集体收涨 贵金属涨幅居前】6月2日,A股三...
OpenAI,正式组建机器人事... 人工智能(AI)领域巨头OpenAI发布公告,宣布大力扩张内部机器人事业部,正式全面切入硬件赛道,实...
星火空间完成近亿元Pre-A轮... 据星火空间消息,6月1日,合肥星火空间科技有限公司完成近亿元Pre-A轮融资。本轮融资由云泽资本和轨...
刚刚,宇树IPO闪电过会!王兴... 智东西 作者 | 许丽思 编辑 | 漠影 智东西6月1日报道,刚刚,宇树通过上交所上市委会议审议。 ...
京东工业发起百川计划 携手上游... 京东工业大模型生态发布会6月1日在北京举行,京东工业携手合作伙伴正式开启“百川计划”,从数据、模型、...
强脑科技预计今年机械手销量大涨... IT之家 6 月 2 日消息,据彭博社 2 日(今天)报道,强脑科技预计,随着中国人形机器人产业快速...
一图看懂差距!iPhone 1... 快科技6月2日消息,iPhone 18 Pro不同版本电池容量不同的相关话题冲上社交平台热搜榜,引发...
iPhone 18 Pro 或... 据科技狐,近日,知名爆料人 Sonny Dickson 分享了 iPhone 18 Pro 全套机模...
武契奇:不排除卸任总统后担任总... 塞尔维亚总统武契奇近期密集释放政坛人事与大选相关信号,明确无意在 2027 年总统任期届满后谋求连任...