python之生产者消费者模型实现详解

yipeiwu_com6年前Python基础

代码及注释如下

#Auther Bob
#--*--conding:utf-8 --*--
#生产者消费者模型,这里的例子是这样的,有一个厨师在做包子,有一个顾客在吃包子,有一个服务员在储存包子,这个服务员我们就可以用queue来实现
import threading
import queue
import time
 
'''
def consumer(p,que):
  id = que.get()
  print("[%s]来吃包子了,我吃到的包子的名字是[%s]" %(p,id))
 
def prodcer(p,que):
  print("[%s]做了2个包子" %(p))
  que.put("baozi[1]")
  print("baozi[1]做好了")
  que.put("baozi[2]")
  print("baozi[2]做好了")
 
if __name__ == '__main__':
  que = queue.Queue()
  p = threading.Thread(target=prodcer,args=("Bob",que))
  c1 = threading.Thread(target=consumer,args=("c1",que))
  c2 = threading.Thread(target=consumer, args=("c2", que))
  c3 = threading.Thread(target=consumer, args=("c3", que))
  p.start()
  c1.start()
  c2.start()
  c3.start()
  # p.join()
 
 
'''
 
 
#上面这个例子,如果没有包子了,但是厨师会不知道,厨师也不会继续做包子,而没有吃到包子的人会一直等待,程序会一直不结束
 
 
 
#我们可以这样做,消费者发现没有包子了,告诉服务员,服务员在告诉厨师,这里我们就会遇到task.down
 
def consumer(p):
  id = que.get()
  print("[%s]来吃包子了,我吃到的包子的名字是[%s]" %(p,id))
  que.task_done()  #如归队列为空了,则会通知que.join,que.join就不会阻塞了
 
"""
 
def prodcer(p):
  while True:
    if que.qsize() < 3:
      # time.sleep(1)
      for i in range(2):
        print("[%s]做了包子[%d]" %(p,i))
        que.put(i)
      que.join() #如果队列一直不为空,则que.join会一直阻塞,如果队列为空,则que.join就不阻塞了
"""
def prodcer(p):
  while True:
    # time.sleep(1)
    for i in range(2):
      print("[%s]做了包子[%d]" %(p,i))
      que.put(i)
    que.join() #如果队列一直不为空,则que.join会一直阻塞,如果队列为空,则que.join就不阻塞了
if __name__ == '__main__':
  que = queue.Queue()
  p = threading.Thread(target=prodcer,args=("Bob1",))
  p2 = threading.Thread(target=prodcer, args=("Bob2",))
  c1 = threading.Thread(target=consumer,args=("c1",))
  c2 = threading.Thread(target=consumer, args=("c2",))
  c3 = threading.Thread(target=consumer, args=("c3",))
  c4 = threading.Thread(target=consumer, args=("c4",))
  c5 = threading.Thread(target=consumer, args=("c5",))
  c6 = threading.Thread(target=consumer, args=("c6",))
  p.start()
  p2.start()
  c1.start()
  c2.start()
  c3.start()
  c4.start()
  c5.start()
  c6.start()
  # p.join()
  # que.task_done()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python集合类型用法分析

本文实例分析了python集合类型用法。分享给大家供大家参考。具体分析如下: python的集合类型和其他语言类似, 是一个无序不重复元素集,我在之前学过的其他的语言好像没有见过这个类型...

Python 图像处理: 生成二维高斯分布蒙版的实例

Python 图像处理: 生成二维高斯分布蒙版的实例

在图像处理以及图像特效中,经常会用到一种成高斯分布的蒙版,蒙版可以用来做图像融合,将不同内容的两张图像结合蒙版,可以营造不同的艺术效果。 这里II 表示合成后的图像,FF 表示前景图,...

解决python3 安装完Pycurl在import pycurl时报错的问题

此次遇到的问题是在import pycurl 时报错 pycurl:libcurl link-time version is older than compile-time versi...

对Python 检查文件名是否规范的实例详解

如下所示: # coding=utf-8 import os import os.path import re import array import cmd import pdb...

用python代码将tiff图片存储到jpg的方法

mac用起来还是有很多不方便的地方,app很局限也都不是很好用,mac自带的截图工具,格式是tiff,需要转成jpg才能在代码中使用,利用python代码很轻松做到了这一点: 打开终端,...