首页 > 其他 > 详细

threading Condition方法

时间:2019-02-26 19:35:46      阅读:277      评论:0      收藏: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()

threading Condition方法

原文:https://blog.51cto.com/windchasereric/2355254

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!