首页 > 编程语言 > 详细

python多线程生产消费

时间:2017-09-24 16:07:20      阅读:216      评论:0      收藏:0      [点我收藏+]
#!/usr/bin/env python
# -*- coding: utf-8 -*-


from threading import Thread
from Queue import Queue
import time

class Producer(Thread):

def __init__(self,name,queue):
self.__name = name
self.__queue = queue
super(Producer,self).__init__()

def run(self):
while 1:
if self.__queue.full():
time.sleep(1)
else:
self.__queue.put(‘bread‘)
time.sleep(1)
print ‘%s produce a bread‘ %(self.__name,)



class Consumer(Thread):

def __init__(self,name,queue):
self.__name = name
self.__queue = queue
super(Consumer,self).__init__()

def run(self):
while 1:
if self.__queue.empty():
time.sleep(1)
else:
self.__queue.get()
time.sleep(1)
print ‘%s eat a bread‘ % (self.__name,)

que = Queue(maxsize=100)

for p in range(3):
name = ‘P%d‘ % (p,)
temp = Producer(name, que)
temp.start()

for item in range(20):
name = ‘C%d‘ % (item,)
temp = Consumer(name, que)
temp.start()


python多线程生产消费

原文:http://www.cnblogs.com/zejin2008/p/7587280.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!