码迷,mamicode.com
首页 > 编程语言 > 详细

python之函数实现生产者消费者模型(开发模型)

时间:2017-02-17 00:52:28      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:python

#!/usr/bin/env /python

import threading
import time
import Queue
import random

#生产者
def Proudcer(name,que):
    while True:
        if que.qsize() < 3: #如果只剩下3个包子就又开始生产包子(如果队列中的数据为3个时)
            que.put(‘baozi‘) #包子入队列
            print ‘%s 生产包子...‘ % name
        else:
            print "%s 仅剩3个包子..."
        time.sleep(random.randrange(5)) #随机在1-5秒内开始生产包子(推迟调用线程的运行,可通过参数secs指秒数,表示进程挂起的时间)

#消费者
def Consumer(name,que):
    while True:
        try:
            que.get_nowait() #消费者消费包子(从队列取数据,且为非阻塞模式,如果队列为空了,则会引发出异常)
            print ‘ %s 消费包子...‘ % name
            time.sleep(random.randrange(3))  #随机在1-3秒内开始消费包子(推迟调用线程的运行,可通过参数secs指秒数,表示进程挂起的时间)
        except Exception:
            print u‘包子已卖完...‘ #捕捉队列为空时引发的异常


#定义一个队列存用来储包子
q = Queue.Queue()

#创建第1个厨师 (也就是线程1,传入name参数:“tantianran”和队列q)
p1 = threading.Thread(target=Proudcer,args=[‘tantianran‘,q])
#创建第2个厨师 (也就是线程2
p2 = threading.Thread(target=Proudcer,args=[‘dengwenqing‘,q])
#启动线程(线程是同时工作)
p1.start()
p2.start()

#创建2个消费者线程分别为c1和c2
c1 = threading.Thread(target=Consumer,args=[‘xiaofeizhe1‘,q])
c2 = threading.Thread(target=Consumer,args=[‘tanyongxing‘,q])
#启动线程(线程是同时工作)
c1.start()
c2.start()


本文出自 “运维交流Q群:223843163” 博客,请务必保留此出处http://freshair.blog.51cto.com/8272891/1898467

python之函数实现生产者消费者模型(开发模型)

标签:python

原文地址:http://freshair.blog.51cto.com/8272891/1898467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!