zoukankan      html  css  js  c++  java
  • 线程_FIFO队列实现生产者消费者

    import threading # 导入线程库
    import time
    from queue import Queue # 队列
    
    class Producer(threading.Thread):
        # 线程的继承类,修改 run 方法
        def run(self):
            global queue
            count = 0
            while True:
                if queue.qsize() <1000:
                    for i in range(100):
                        count = count + 1
                        msg = '生成产品'+str(count)
                        queue.put(msg)#向队列中添加元素
                        print(msg)
                time.sleep(1)
    
    
    class Consumer(threading.Thread):
        # 线程的继承类,修改 run 方法
        def run(self):
            global queue
            while True:
                if queue.qsize() >100 :
                    for i in range(3):
                        msg = self.name + '消费了' + queue.get() #获取数据
                        # queue.get()获取到数据
                        print(msg)
                time.sleep(1)
    
    
    if __name__ == '__main__':
        queue = Queue()
        # 创建一个队列
    
        for i in range(500):
            queue.put('初始产品'+str(i))
            # 在 queue 中放入元素 使用 put 函数
    
        for i in range(2):
            p = Producer()
            p.start()
        #     调用Producer类的run方法
        for i in range(5):
            c = Consumer()
            c.start()

    2020-05-07

  • 相关阅读:
    架构基础-CAP原理
    Nginx基础
    Nginx基础
    Nginx基础
    Nginx基础
    Nginx基础
    Nginx基础
    Nginx基础
    CentOS 7 架设LNMP动态网站
    Linux下文件描述符
  • 原文地址:https://www.cnblogs.com/hany-postq473111315/p/12845511.html
Copyright © 2011-2022 走看看