生产者消费者模型

# 生产者消费者模型
# 在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程
# 如果生产者速度快而消费者处理速度慢,或生产者处理速度慢而消费者处理速度快,这样就会发生等待
# 为了解决这个问题于是就引入了生产者和消费者模式
# 生产者消费者模式是通过一个容器来解决生产者与消费者强耦合问题
# 生产者和消费者不直接通读,而通过阻塞队列来进行通讯,生产者—阻塞对列—消费者
# 阻塞队列相当于一个缓冲区,平衡了生产者和消费者的处理能力
# 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()

 

posted @ 2018-08-18 21:46  四十不惑的编程之路  阅读(125)  评论(0编辑  收藏  举报