zoukankan      html  css  js  c++  java
  • 生产者消费者模型

    # 生产者消费者模型
    # 在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程
    # 如果生产者速度快而消费者处理速度慢,或生产者处理速度慢而消费者处理速度快,这样就会发生等待
    # 为了解决这个问题于是就引入了生产者和消费者模式
    # 生产者消费者模式是通过一个容器来解决生产者与消费者强耦合问题
    # 生产者和消费者不直接通读,而通过阻塞队列来进行通讯,生产者—阻塞对列—消费者
    # 阻塞队列相当于一个缓冲区,平衡了生产者和消费者的处理能力
    # task_down()与join()成对使用
    
    import time, random, queue, threading
    
    q = queue.Queue()  # 创建对列
    
    
    def Producer(name):  # 生产者
        count = 0
        while count < 10:   # 向对列中加入10条数据
            print('marking...')
            time.sleep(random.randrange(3))     # 生产beefnoodle的时间
            q.put(count)    # 将count放入对列
            print('Porducer %s has produced %s beefnoodle' % (name, count))
            count += 1
            q.task_done()   # 告诉对列q,已经put
            print('ok')
    
    
    def Consumer(name):
        count = 0
        while count < 10:   # 向对列中加入10条数据
            time.sleep(random.randrange(4))
            # if not q.empty():    # 判断对列是否为空
            data = q.get()
            print('waiting...')
            q.join()    # 告诉对列q,需要get
            print('Consumer %s has eat %s beefnoodle' % (name, data))
            # else:
            #     print('-----no beefnoodle anymore-----')
            count += 1
    
    
    
    
    p1 = threading.Thread(target=Producer, args=('生产者A',))
    c1 = threading.Thread(target=Consumer, args=('消费者B',))
    c2 = threading.Thread(target=Consumer, args=('消费者C',))
    c3 = threading.Thread(target=Consumer, args=('消费者D',))
    
    
    p1.start()
    c1.start()
    c2.start()
    c3.start()
  • 相关阅读:
    栈的理解(出、入栈)
    javascript实现可以拖动的层示例(层拖动,兼容IE/FF)
    C# 队列 堆栈
    从0开始做Windows Phone 7开发
    C#写系统日志
    一位软件工程师的6年总结
    向Android模拟器发短信打电话
    office2010激活方法
    常用正则表达式
    JaveScript获得鼠标位置
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9498788.html
Copyright © 2011-2022 走看看