之前用C++写过一篇生产者消费者的实现。

生产者和消费者主要是处理互斥和同步的问题:

队列作为缓冲区,需要互斥操作

队列中没有产品,消费者需要等待,直到生产者放入产品并通知它。队列慢的情况类似。

这里我使用list模拟Python标准库的Queue,这里我设置一个大小限制为5:

SyncQueue.py

from threading import Lock
from threading import Condition
class Queue():
def __init__(self):
self.mutex = Lock()
self.full = Condition(self.mutex)
self.empty = Condition(self.mutex)
self.data = [] def push(self, element):
self.mutex.acquire()
while len(self.data) >= 5:
self.empty.wait() self.data.append(element)
self.full.notify()
self.mutex.release() def pop(self):
self.mutex.acquire()
while len(self.data) == 0:
self.full.wait()
data = self.data[0]
self.data.pop(0)
self.empty.notify()
self.mutex.release() return data if __name__ == '__main__':
q = Queue()
q.push(10)
q.push(2)
q.push(13) print q.pop()
print q.pop()
print q.pop()

这是最核心的代码,注意里面判断条件要使用while循环。

接下来是生产者进程,producer.py

from threading import Thread
from random import randrange
from time import sleep
from SyncQueue import Queue class ProducerThread(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def run(self):
while True:
data = randrange(0, 100)
self.queue.push(data)
print 'push %d' % (data)
sleep(1) if __name__ == '__main__':
q = Queue()
t = ProducerThread(q)
t.start()
t.join()

消费者,Condumer.py

from threading import Thread
from time import sleep
from SyncQueue import Queue class ConsumerThread(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def run(self):
while True:
data = self.queue.pop()
print 'pop %d' % (data)
sleep(1) if __name__ == '__main__':
q = Queue()
t = ConsumerThread(q)
t.start()
t.join()

最后我们写一个车间类,可以指定线程数量:

from SyncQueue import Queue
from Producer import ProducerThread
from Consumer import ConsumerThread class WorkShop():
def __init__(self, producerNums, consumerNums):
self.producers = []
self.consumers = []
self.queue = Queue()
self.producerNums = producerNums
self.consumerNums = consumerNums
def start(self):
for i in range(self.producerNums):
self.producers.append(ProducerThread(self.queue))
for i in range(self.consumerNums):
self.consumers.append(ConsumerThread(self.queue))
for i in range(len(self.producers)):
self.producers[i].start()
for i in range(len(self.consumers)):
self.consumers[i].start()
for i in range(len(self.producers)):
self.producers[i].join()
for i in range(len(self.consumers)):
self.consumers[i].join() if __name__ == '__main__':
w = WorkShop(3, 4)
w.start()

最后写一个main模块:

from WorkShop import WorkShop

if __name__ == '__main__':
w = WorkShop(2, 3)
w.start()

使用Python实现生产者消费者问题的更多相关文章

  1. python进程——生产者消费者

    生产者消费者模型介绍 为什么要使用生产者消费者模型 生产者指的是生产数据的任务,消费者指的是处理数据的任务,在并发编程中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完 ...

  2. python之生产者消费者模型

    #Auther Bob #--*--conding:utf-8 --*-- #生产者消费者模型,这里的例子是这样的,有一个厨师在做包子,有一个顾客在吃包子,有一个服务员在储存包子,这个服务员我们就可以 ...

  3. Python多线程-生产者消费者模型

    用多线程和队列来实现生产者消费者模型 # -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading imp ...

  4. (python)生产者消费者模型

    生产者消费者模型当中有两大类重要的角色,一个是生产者(负责造数据的任务),另一个是消费者(接收造出来的数据进行进一步的操作). 为什么要使用生产者消费者模型? 在并发编程中,如果生产者处理速度很快,而 ...

  5. python 之生产者消费者模型

    进程实现: import time,random from multiprocessing import Process,Queue def producer(name,q): count= 0 wh ...

  6. python并发——生产者消费者信号量实现

    介绍 写扫描器的时候,需要让资产扫描结果一出来(生产者),另外一边就会开个线程去运行漏洞扫描(消费者). 但是又不能让结果没出来,另外一边消费者就开始干活了. 代码 # *coding:UTF-8 * ...

  7. python实现生产者消费者模型

    生产者消费之模型就是,比如一个包子铺,中的顾客吃包子,和厨师做包子,不可能是将包子一块做出来,在给顾客吃,但是单线程只能这麽做,所以用多线程来执行,厨师一边做包子,顾客一边吃包子,当顾客少时,厨师做的 ...

  8. python 多线程 生产者消费者

    import threading import time import logging import random import Queue logging.basicConfig(level=log ...

  9. Python学习笔记——进阶篇【第九周】———线程、进程、协程篇(队列Queue和生产者消费者模型)

    Python之路,进程.线程.协程篇 本节内容 进程.与线程区别 cpu运行原理 python GIL全局解释器锁 线程 语法 join 线程锁之Lock\Rlock\信号量 将线程变为守护进程 Ev ...

随机推荐

  1. EAScript 2016的新增语法(1)

    1)let 语法,这个和var的声明类似,但是,只存在于其所在的代码块里. 举例: var x=1 console.log(x) { let x=2 console.log(x) } console. ...

  2. hdu 5167(dfs)

    Fibonacci Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total S ...

  3. 使用Rancher管理Docker

    使用命令: sudo docker run -it -d --restart=always -p : --name docker-rancher rancher/server 为了更快速的下载应用,推 ...

  4. (17)python 网络编程

    TCP连接的断点是由一个IP地址和一个端口号来唯一标识的 客户端/服务器 客户端总是最开始申请连接的一端,服务器则是等待客户端连接的一段 服务器的端口号如果不是特殊用土的一般应该大于1024,客户端则 ...

  5. 为何jsp 在resin下乱码,但在tomcat下却工作良好的问题

    关于JSP页面中的pageEncoding和contentType两种属性的区别:       pageEncoding是jsp文件本身的编码       contentType的charset是指服 ...

  6. 子域名/目录暴力工具Gobuster

    子域名/目录暴力工具Gobuster   Gobuster是Kali Linux默认安装的一款暴力扫描工具.它是使用Go语言编写的命令行工具,具备优异的执行效率和并发性能.该工具支持对子域名和Web目 ...

  7. [CTSC2018]混合果汁(二分答案+主席树)

    考场上写了60分的二分答案,又写了15分的主席树,然后就弃了.. 合起来就A了啊!主席树忘了开20倍空间最后还炸掉了. 最水的签到题被我扔了,主要还是不会用线段树求前缀和. 做法应该是比较显然的,首先 ...

  8. [xsy1100]东舰停战不可避

    没有三点共线 这题的思想来源于JOI2011-2012春季训练合宿Day2T2,原题是个大毒瘤题(p.s.场上有人A,真的可怕),这题作为原题要用到的的一个结论而存在 点有两种颜色,先考虑对所有点做凸 ...

  9. 【动态规划】【记忆化搜索】CODEVS 3415 最小和 CodeVS原创

    f(l,r,i)表示第i段截第l位到第r位时,当前已经得到的价格最小值,可以很显然地发现,这个是没有后效性的,因为对之后截得的段都不造成影响. 注意水彩笔数=1的特判. 递归枚举当前段的r求解(∵l是 ...

  10. 【莫队算法】【权值分块】bzoj3809 Gty的二逼妹子序列

    如题. #include<cstdio> #include<algorithm> #include<cmath> using namespace std; int ...