资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

threadingCondition方法

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

创新互联云计算的互联网服务提供商,拥有超过13年的服务器租用、四川服务器托管、云服务器、虚拟空间、网站系统开发经验,已先后获得国家工业和信息化部颁发的互联网数据中心业务许可证。专业提供云主机、虚拟空间、域名申请、VPS主机、云服务器、香港云服务器、免备案服务器等。

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

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

当前题目:threadingCondition方法
文章URL:http://cdkjz.cn/article/pdppdd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220