Python 单向队列Queue模块详解

单向队列Queue,先进先出

'''A multi-producer, multi-consumer queue.'''

try:
import threading
except ImportError:
import dummy_threading as threading
from collections import deque
from heapq import heappush, heappop
from time import monotonic as time __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] class Empty(Exception):
'Exception raised by Queue.get(block=0)/get_nowait().'
pass class Full(Exception):
'Exception raised by Queue.put(block=0)/put_nowait().'
pass class Queue:
'''Create a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite.
''' def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize) # mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock() # Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex) # Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex) # Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0 def task_done(self):
'''Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete. If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue). Raises a ValueError if called more times than there were items
placed in the queue.
'''
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished def join(self):
'''Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
'''
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait() def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize() def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used. To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method.
'''
with self.mutex:
return not self._qsize() def full(self):
'''Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used.
'''
with self.mutex:
return 0 < self.maxsize <= self._qsize() def put(self, item, block=True, timeout=None):
'''Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
with self.not_full:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify() def get(self, block=True, timeout=None):
'''Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
with self.not_empty:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while not self._qsize():
remaining = endtime - time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item def put_nowait(self, item):
'''Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
'''
return self.put(item, block=False) def get_nowait(self):
'''Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False) # Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held # Initialize the queue representation
def _init(self, maxsize):
self.queue = deque() def _qsize(self):
return len(self.queue) # Put a new item in the queue
def _put(self, item):
self.queue.append(item) # Get an item from the queue
def _get(self):
return self.queue.popleft() class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first). Entries are typically tuples of the form: (priority number, data).
''' def _init(self, maxsize):
self.queue = [] def _qsize(self):
return len(self.queue) def _put(self, item):
heappush(self.queue, item) def _get(self):
return heappop(self.queue) class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.''' def _init(self, maxsize):
self.queue = [] def _qsize(self):
return len(self.queue) def _put(self, item):
self.queue.append(item) def _get(self):
return self.queue.pop()

queue

创建Deque序列:

Python中,队列是线程间最常用的交换数据的形式。Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。

创建一个“队列”对象

import queue
q = queue.Queue(maxsize = 10)

Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。

将一个值放入队列中

q.put(10)

调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为
1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。

把一个项目放入队列中。如果可选的args“块”为真,“超时”不为(默认),如果需要,可以在一个空闲插槽之前阻止。如果“超时”一个非负数的数字,它会阻塞最多的“超时”秒,并提高如果在此期间没有空闲插槽,则完全例外。否则(' block '是假的),如果空闲插槽,在队列上放置一个项目立即可用,否则将引发完整的异常(“超时”)

将一个值从队列中取出

q.get()
#!/usr/bin/python3

import queue
#创建队列
q = queue.Queue(maxsize = 10)
q.put(11)
q.put(12)
q.put(13)
print(q.qsize())
print(q.get())
print(q.get())
print(q.get())

执行结果:

3
11
12
13

调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。

Python Queue模块有三种队列及构造函数:

  • 1、Python Queue模块的FIFO队列先进先出。 class Queue.Queue(maxsize)
  • 2、LIFO类似于堆,即先进后出。 class Queue.LifoQueue(maxsize)
  • 3、还有一种是优先级队列级别越低越先出来。 class Queue.PriorityQueue(maxsize)

此包中的常用方法(q = Queue.Queue()):

  • q.qsize() 返回队列的大小
  • q.empty() 如果队列为空,返回True,反之False
  • q.full() 如果队列满了,返回True,反之False
  • q.full 与 maxsize 大小对应
  • q.get([block[, timeout]]) 获取队列,timeout等待时间
  • q.get_nowait() 相当q.get(False)
  • 非阻塞 q.put(item) 写入队列,timeout等待时间
  • q.put_nowait(item) 相当q.put(item, False)
  • q.task_done() 在完成一项工作之后,q.task_done() 函数向任务已经完成的队列发送一个信号
  • q.join() 实际上意味着等到队列为空,再执行别的操作

范例:

  • 实现一个线程不断生成一个随机数到一个队列中(考虑使用Queue这个模块)
  • 实现一个线程从上面的队列里面不断的取出奇数
  • 实现另外一个线程从上面的队列里面不断取出偶数
#!/usr/bin/env python
#coding:utf8
import random,threading,time
from Queue import Queue
#Producer thread
class Producer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self,name=t_name)
self.data=queue
def run(self):
for i in range(10): #随机产生10个数字 ,可以修改为任意大小
randomnum=random.randint(1,99)
print "%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), randomnum)
self.data.put(randomnum) #将数据依次存入队列
time.sleep(1)
print "%s: %s finished!" %(time.ctime(), self.getName()) #Consumer thread
class Consumer_even(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self,name=t_name)
self.data=queue
def run(self):
while 1:
try:
val_even = self.data.get(1,5) #get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒
if val_even%2==0:
print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(),self.getName(),val_even)
time.sleep(2)
else:
self.data.put(val_even)
time.sleep(2)
except: #等待输入,超过5秒 就报异常
print "%s: %s finished!" %(time.ctime(),self.getName())
break
class Consumer_odd(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self, name=t_name)
self.data=queue
def run(self):
while 1:
try:
val_odd = self.data.get(1,5)
if val_odd%2!=0:
print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val_odd)
time.sleep(2)
else:
self.data.put(val_odd)
time.sleep(2)
except:
print "%s: %s finished!" % (time.ctime(), self.getName())
break
#Main thread
def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer_even = Consumer_even('Con_even.', queue)
consumer_odd = Consumer_odd('Con_odd.',queue)
producer.start()
consumer_even.start()
consumer_odd.start()
producer.join()
consumer_even.join()
consumer_odd.join()
print 'All threads terminate!' if __name__ == '__main__':
main()

  

Python 单向队列Queue模块详解的更多相关文章

  1. Python 双向队列Deque、单向队列Queue 模块使用详解

    Python 双向队列Deque 模块使用详解 创建双向队列Deque序列 双向队列Deque提供了类似list的操作方法: #!/usr/bin/python3 import collections ...

  2. (转)python之os,sys模块详解

    python之sys模块详解 原文:http://www.cnblogs.com/cherishry/p/5725184.html sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和 ...

  3. python标准库介绍——32 Queue 模块详解

    Queue 模块 ``Queue`` 模块提供了一个线程安全的队列 (queue) 实现, 如 [Example 3-2 #eg-3-2] 所示. 你可以通过它在多个线程里安全访问同个对象. ==== ...

  4. Python之队列queue模块使用 常见问题与用法

    python 中,队列是线程间最常用的交换数据的形式.queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外. 1. 阻塞模式 import queue q = queu ...

  5. Python3.5 queue模块详解

    queue介绍 queue是python中的标准库,俗称队列,可以直接import 引用,在python2.x中,模块名为Queue 在python中,多个线程之间的数据是共享的,多个线程进行数据交换 ...

  6. (转)Python3.5 queue模块详解

    原文:https://www.cnblogs.com/CongZhang/p/5274486.html queue介绍 queue是python中的标准库,俗称队列,可以直接import 引用,在py ...

  7. python里面的xlrd模块详解(一)

    那我就一下面积个问题对xlrd模块进行学习一下: 1.什么是xlrd模块? 2.为什么使用xlrd模块? 3.怎样使用xlrd模块? 1.什么是xlrd模块? python操作excel主要用到xlr ...

  8. python中正则表达式re模块详解

    正则表达式是处理字符串的强大工具,它有自己特定的语法结构,有了它,实现字符串的检索,替换,匹配验证都不在话下. 当然,对于爬虫来说,有了它,从HTML里提取想要的信息就非常方便了. 先看一下常用的匹配 ...

  9. python里面的xlrd模块详解

    那我就一下面积个问题对xlrd模块进行学习一下: 1.什么是xlrd模块? 2.为什么使用xlrd模块? 3.怎样使用xlrd模块? 1.什么是xlrd模块? ♦python操作excel主要用到xl ...

随机推荐

  1. Ansj分词的使用

    jar包下载地址:http://download.csdn.net/download/jj12345jj198999/6020541 博客地址:http://blog.csdn.net/a822631 ...

  2. Hadoop调度框架

        大数据协作框架是一个桐城,就是Hadoop2生态系统中几个辅助的Hadoop2.x框架.主要如下: 1,数据转换工具Sqoop 2,文件搜集框架Flume 3,任务调度框架Oozie 4,大数 ...

  3. 人物丨让小三吐血,让原配泣血——24K渣男郎咸平

    http://url.cn/5swgmythttps://www.toutiao.com/i6650650793743483395人物丨让小三吐血,让原配泣血——24K渣男郎咸平 人物丨让小三吐血,让 ...

  4. TCP/IP详解之IP协议

    1.IP协议 IP协议是TCP/IP协议的核心,所有的TCP,UDP,IMCP,IGCP的数据都以IP数据格式传输.要注意的是,IP不是可靠的协议,这是说,IP协议没有提供一种数据未传达以后的处理机制 ...

  5. (转)编码剖析Spring装配基本属性的原理

    http://blog.csdn.net/yerenyuan_pku/article/details/52856465 上回我们已经讲到了Spring依赖注入的第一种方式,现在我们来详解第二种方式,须 ...

  6. ListView中含有EditText时候--要命的焦点问题迎刃而解

    最近做项目的时候遇到了一个问题,就是在ListView的item上面含有一个EditText,要求是这样: 1当点击item的时候,item可以点击; 2当点击EditText的时候EditText也 ...

  7. mybatis传入参数类型parameterType和输出结果类型resultType详解

    前言 Mybatis的Mapper文件中的select.insert.update.delete元素中都有一个parameterType和resultType属性,parameterType属性用于对 ...

  8. (二)VMware Harbor 安装

    转自:https://blog.csdn.net/qq_33633013/article/details/82217277 一.环境.软件准备 harbor 需要依赖docker,compose工具, ...

  9. @click.native 会触发原生 click事件 vue

    @click.native 会触发原生 click事件 vue

  10. ES6 第五章 字符串的新增方法 具体参照 http://es6.ruanyifeng.com

    1.FormCodePoint 对象方法 用于从 Unicode 码点返回对应字符,可以识别原来es5不能识别的大于0xFFFF的码点. String.fromCodePoint(0x20BB7) / ...