码迷,mamicode.com
首页 > 编程语言 > 详细

Python 单向队列Queue模块详解

时间:2017-07-30 17:03:51      阅读:975      评论:0      收藏:0      [点我收藏+]

标签:call   eth   run   tac   rect   count   ase   先进先出   一个   

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模块详解

标签:call   eth   run   tac   rect   count   ase   先进先出   一个   

原文地址:http://www.cnblogs.com/chenlin163/p/7259321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!