zoukankan      html  css  js  c++  java
  • python 多线程笔记(6)-- 生产者/消费者模式(续)

    用 threading.Event() 也可以实现生产者/消费者模式

    (自己拍脑袋想出来的,无法知道其正确性,请大神告知为谢!)

    import threading
    import time
    import random
    
    
    products = 20
    
     
    class Producer(threading.Thread):
        '''生产者'''
        ix = [0] # 生产者实例个数
                 # 闭包,必须是数组,不能直接 ix = 0
        
        def __init__(self):
            super().__init__()
            self.ix[0] += 1
            self.setName('生产者' + str(self.ix[0]))
     
        def run(self):
            global producer_signal, products
            
            while True:
                if products < 10:
                    if not producer_signal.is_set(): producer_signal.set()
                    products += 1;
                    print("{}:库存告急。我努力生产了1件产品,现在产品总数量 {}".format(self.getName(), products))
                else:
                    print("{}:库存充足。我努力生产了0件产品,现在产品总数量 {}".format(self.getName(), products))
                    if producer_signal.is_set(): producer_signal.wait()
                time.sleep(random.randrange(1,4))
            
            
    class Consumer(threading.Thread):
        '''消费者'''
        ix = [0] # 消费者实例个数
                 # 闭包,必须是数组,不能直接 ix = 0
                 
        def __init__(self):
            super().__init__()
            self.ix[0] += 1
            self.setName('消费者' + str(self.ix[0]))
     
        def run(self):
            global consumer_signal, products
            
            while True:
                if products > 1:
                    if not consumer_signal.is_set(): consumer_signal.set()
                    products -= 1;
                    print("{}:我消费了1件产品,现在产品数量 {}".format(self.getName(), products))
                else:
                    print("{}:我消费了0件产品。现在产品数量 {}".format(self.getName(), products))
                    if consumer_signal.is_set(): consumer_signal.wait()
                time.sleep(random.randrange(2,6))
     
    
            
            
    if __name__ == "__main__":
    
        producer_signal = threading.Event()
        consumer_signal = threading.Event()
        
        for i in range(2):
            p = Producer()
            p.start()
     
        for i in range(10):
            c = Consumer()
            c.start()
     
  • 相关阅读:
    Qt 跟踪鼠标事件:setMouseTracking(true)
    Qt setMouseTracking使用
    Qt QGraphicsItem 鼠标点击事件编程方法
    Qt QGraphicsItem信号连接有关问题
    Qt 自定义QGraphicsItem
    Qt 视图框架QGraphicsItem
    Qt QGraphicsItem要点 积累
    Qt Q_UNUSED() 方法的使用
    Qt 绘图之QGraphicsScene QGraphicsView QGraphicsItem详解
    Qt 使用QGraphicsItem绘制复杂的图形
  • 原文地址:https://www.cnblogs.com/hhh5460/p/5178878.html
Copyright © 2011-2022 走看看