温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

threading Condition方法

发布时间:2020-07-26 15:38:34 来源:网络 阅读:472 作者:windcharger 栏目:编程语言

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

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

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()
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI