您的位置:首页 > 编程语言 > Python开发

python多线程编程:生成者和消费者

2015-09-18 16:20 316 查看
<pre name="code" class="javascript">#!/usr/bin/env python
#coding:utf-8
import threading
import Queue
import time
import random

def produce(name,que):
while True:
if que.qsize()<3:
que.put('baozi')
print '%s 生产者' %name
time.sleep(random.randrange(2))

def comsum(name,que):
while True:
try:
que.get()
print '%s 消费者' %name
except Exception:
print u'没有产品了'
time.sleep(random.randrange(5))

q = Queue.Queue()
t1 = threading.Thread(target=produce,args=['cc1',q])
t2 = threading.Thread(target=produce,args=['cc2',q])
t1.start()
t2.start()
c1 = threading.Thread(target=comsum,args=['mm1',q])
c2 = threading.Thread(target=comsum,args=['mm2',q])
c1.start()
c2.start()


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: