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()
  • 相关阅读:
    [Leetcode] Median of Two Sorted Arrays
    [Jobdu] 题目1463:招聘会
    [Leetcode] Merge Two Sorted Lists
    [Leetcode] Combinations
    [Leetcode] Populating Next Right Pointers in Each Node II
    [Leetcode] Insertion Sort List
    redis在Web中的使用
    设计模式:单例模式
    设计模式:基本法则
    设计模式:工厂模式
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9498788.html
Copyright © 2011-2022 走看看