`
lingshangwen
  • 浏览: 61153 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

python:Queue模块

阅读更多

 queue — A synchronized queue class

Note

 

The Queue module has been renamed to queue in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.

Implements three types of queue whose only difference is the order that the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack). With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first.

The Queue module defines the following classes and exceptions:

class Queue.Queue(maxsize)
Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
class Queue.LifoQueue(maxsize)

Constructor for a LIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.

New in version 2.6.

class Queue.PriorityQueue(maxsize)

Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data).

New in version 2.6.

exception Queue.Empty
Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty.
exception Queue.Full
Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full.

See also

 

collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft()operations that do not require locking.

 Queue Objects

Queue objects (QueueLifoQueue, or PriorityQueue) provide the public methods described below.

Queue.qsize()
Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.
Queue.empty()
Return True if the queue is empty, False otherwise. If empty() returns True it doesn’t guarantee that a subsequent call to put() will not block. Similarly, if empty() returns False it doesn’t guarantee that a subsequent call to get() will not block.
Queue.full()
Return True if the queue is full, False otherwise. If full() returns True it doesn’t guarantee that a subsequent call to get() will not block. Similarly, if full() returns False it doesn’t guarantee that a subsequent call to put() will not block.
Queue.put(item[block[timeout]])

Put 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 positive 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).

New in version 2.3: The timeout parameter.

Queue.put_nowait(item)
Equivalent to put(item, False).
Queue.get([block[timeout]])

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 positive number, it blocks at most timeout seconds and raises the Emptyexception 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).

New in version 2.3: The timeout parameter.

Queue.get_nowait()
Equivalent to get(False).

Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads.

Queue.task_done()

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.

New in version 2.5.

Queue.join()

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 that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.

New in version 2.5.

Example of how to wait for enqueued tasks to be completed:

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.setDaemon(True)
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

分享到:
评论

相关推荐

    Python3 queue队列模块详细介绍

    queue是python中的标准库,俗称队列。这篇文章给大家介绍了Python3 queue队列模块,包括模块中的常用方法及构造函数,需要的朋友参考下吧

    python队列queue模块详解

    主要为大家详细介绍了python队列queue模块的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    Python Queue模块详细介绍及实例

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

    python模块

    * DBM-style 数据库模块:python提供了打了的modules来支持UNIX DBM-style数据库文件。dbm模块用来读取标准的UNIX-dbm数据库文件,gdbm用来读取GNU dbm数据库文件,dbhash用来读取Berkeley DB数据库文件。所有的这些...

    Python Queue模块详解

    Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。 创建一个“队列”对象 import Queue q = Queue.Queue(maxsize = 10) Queue.Queue类即是一个队列的同步实现。队列长度可为无限...

    【Python资源】 通过 queue 队列及时刷新 tkinter 界面显示时间的 demo 案例

    这个 Python Demo 演示了如何结合 queue 模块和 tkinter 库来创建一个能够即时更新显示时间的图形用户界面(GUI)。通过 queue 队列,我们可以将更新 GUI 的任务安全地传递给主线程,从而避免因为直接在子线程中更新...

    Python多线程编程(一):threading模块综述

    在Python中我们主要是通过thread和 threading这两个模块来实现的,其中Python的threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用 threading模块实现多线程编程。这篇文章我们主要来看看...

    python模块详解

    python模块详解 各个模块的详解 核心模块 1.1. 介绍 1.2. _ _builtin_ _ 模块 1.3. exceptions 模块 1.4. os 模块 1.5. os.path 模块 1.6. stat 模块 1.7. string 模块 1.8. re 模块 1.9. math 模块 1.10....

    Python中使用Queue和Condition进行线程同步的方法

    主要介绍了Python中使用Queue模块和Condition对象进行线程同步的方法,配合threading模块下的线程编程进行操作的实例,需要的朋友可以参考下

    Python Queue(队列).docx

    Queue模块实现了多生产者、多消费者队列。当必须在多个线程之间安全地交换信息时,它在线程编程中特别有用,``实现了所有必需的锁定语义。 一、该模块实现了三种类型的队列,它们的区别仅在于检索条目的顺序: 1、...

    Python线程threading模块用法详解

    另请参见mutex和Queue模块。 该dummy_threading模块适用于threading因thread缺失而无法使用的情况 。 注意: 从Python 2.6开始,该模块提供 符合 PEP 8的别名和属性,以替换camelCase受Java的线程API启发的名称。此...

    Queue 实现生产者消费者模型(实例讲解)

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

    Python进程间通信Queue消息队列用法分析

    本文实例讲述了Python进程间通信Queue消息队列用法。分享给大家供大家参考,具体如下: 进程间通信-Queue Process之间有时需要通信,操作系统提供了很多机制来实现进程间的通信。 1. Queue的使用 可以使用...

    【python内功修炼004】:并发编程之joinableQueue模块

    文章目录一:joinableQueue的介绍二:常用方法三:代码示例 一:joinableQueue的介绍 JoinableQueue([maxsize])模块 创建可连接的共享进程...Queue常用方法:【python内功修炼002】:并发编程之多进程实例 方法 功能

    python进程间通信Queue工作过程详解

    可以使用multiprocessing模块的Queue实现多进程之间的数据传递,Queue本身是一个消息列队程序,首先用一个小实例来演示一下Queue的工作原理: import multiprocessing q = multiprocessing.Queue(3) # 初始化的...

Global site tag (gtag.js) - Google Analytics