之前用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. PLSQL Developer 运用Profiler 分析存储过程性能

    最近应公司需要,需要编写ORACLE存储过程.本人新手,在完成存储过程的编写后,感觉需要对存储过程中各个语句的执行时间进行分析,以便 对整个存储过程进行优化. 由于用的是PLSQL Developer ...

  2. IOS UITableViewUITableView小技巧--实现cell向左滑动删除,编辑等功能

    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return Y ...

  3. ros中删除某个包之后用apt安装的包找不到

    原因是工作空间devel里还存有原来的二进制可执行文件,将build和devel内容全删除后再catkin_make就好了

  4. 浅谈C#多线程与UI响应

    www.educity.cn     发布者:shenywww                    来源:网络转载                     发布日期:2014年10月06日      ...

  5. Sublime text3 插件ColorPicker(调色板)不能使用快捷键的解决方法

    我的原因是:convertToUTF8和ColorPicker快捷键冲突,convertoUTF8的默认转换GBK的快捷键 和 ColorPicker打开调色板的快捷键都是ctrl+shift+c . ...

  6. 欧拉图和欧拉圈-Play On Words(UVa10129)

    欧拉路和欧拉圈,简言之就是,从无向图的一个结点出发,走一条路/圈,每条边恰好经过一次,即一笔画问题 欧拉定理:一个无向图最多只有两个奇结点,那么我们就从一个奇结点出发,到另一个结点为之,一定有一条欧拉 ...

  7. Python与数据结构[4] -> 散列表[0] -> 散列表与散列函数的 Python 实现

    散列表 / Hash Table 散列表与散列函数 散列表是一种将关键字映射到特定数组位置的一种数据结构,而将关键字映射到0至TableSize-1过程的函数,即为散列函数. Hash Table: ...

  8. Codeforces Round 253 (Div. 2)

    layout: post title: Codeforces Round 253 (Div. 2) author: "luowentaoaa" catalog: true tags ...

  9. 学习LSM(Linux security module)之三:Apparmor的前世今生和基本使用

    感冒了,感觉一脑子浆糊,真是蛋疼. 先粗略讲一些前置知识. 一:MAC和DAC DAC(Discretionary Access Control),自主访问控制,是最常用的一类访问控制机制,意思为主体 ...

  10. [Contest20180318]求和

    题意:求$\sum\limits_{i=1}^n\sum\limits_{j=1}^i\sum\limits_{k=1}^i(i,j,k)$ 先令$f(n)=\sum\limits_{i=1}^n\s ...