从下面图中可以发现生产者和消费者之间用中间类似一个队列一样的东西串起来。这个队列可以想像成一个存放产品的“仓库”,生产者只需要关心这个“仓库”,并不需要关心具体的消费者,对于生产者而言甚至都不知道有这些消费者存在。对于消费者而言他也不需要关心具体的生产者,到底有多少生产者也不是他关心的事情,他只要关心这个“仓库”中还有没有东西。这种模型是一种松耦合模型。这样可以回答我上面提出的第一个问题。这个模型的产生就是为了复用和解耦。

代码实现:
#!/usr/bin/env Python
#coding:utf-8
from Queue import Queue
from threading import Thread
from time import sleep
class Producer(Thread):
def __init__(self, queue, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None):
Thread.__init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None)
self.queue = queue
def run(self):
while True:
if self.queue.full():
print '\033[31m生产满了\033[0m'
sleep(2)
else:
queue.put('包子')
print '生产了一个包子'
sleep(2)
class Consumer(Thread):
def __init__(self, queue, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None):
Thread.__init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None)
self.queue = queue
def run(self):
while True:
if self.queue.empty():
print '\033[31m没有包子了\033[0m'
sleep(2)
else:
queue.get()
print '消费了一个包子'
sleep(2)
queue = Queue(maxsize=100)
'''生产者'''
pr = Producer(queue)
pr.start()
'''消费者'''
for i in range(2):
con = Consumer(queue)
con.start()
下面关于Python的文章您也可能喜欢,不妨参考下:
《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] 下载见 http://www.linuxidc.com/Linux/2013-06/85425.htm
Python教程PDF合集下载 http://www.linuxidc.com/Linux/2017-04/143278.htm
零基础如何入门Python http://www.linuxidc.com/Linux/2016-10/136485.htm
Ubuntu 14.04安装Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm
CentOS 6.5 脚本自动化装 Python2.6升级2.7 http://www.linuxidc.com/Linux/2017-02/140406.htm
CentOS上源码安装Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm
Ubuntu 14.04下Python数据处理环境搭建 http://www.linuxidc.com/Linux/2017-01/139568.htm
Python Paramiko模块安装和使用 http://www.linuxidc.com/Linux/2017-01/139973.htm
《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm
在CentOS 6.5上安装Python2.7 http://www.linuxidc.com/Linux/2016-10/136206.htm
Ubuntu 14.04 LTS下编译安装Open Babel和Python语言绑定 http://www.linuxidc.com/Linux/2017-01/139569.htm
Python常见数据结构整理 http://www.linuxidc.com/Linux/2017-02/140613.htm
本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-05/143819.htm
