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


<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()       
    
 
 

猜你喜欢

转载自blog.csdn.net/hui_yong/article/details/48548233