`
lingshangwen
  • 浏览: 62014 次
  • 性别: 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队列模块详细介绍

    Python3的`queue`模块是线程安全的数据结构,它实现了多线程环境下的队列操作,主要用于在并发环境中管理任务和数据交换。队列在计算机科学中是一种基础数据结构,遵循特定的出队和入队规则,如先进先出(FIFO)、...

    python队列queue模块详解

    Python的`queue`模块是设计用于多线程和多进程环境中的并发数据结构,它提供了线程安全的数据访问。队列是一种先进先出(FIFO)的数据结构,常用于线程间的通信,确保数据的有序处理。在Python中,`queue`模块提供了...

    Fundamentals of Python:Data Structures 数据结构(Python语言描述)全书配套代码

    Python的collections模块提供了Queue类来实现队列。 7. **链表(Linked Lists)** 虽然Python内置数据结构中没有直接提供链表,但理解链表的概念很重要,特别是在讨论复杂数据结构时。链表每个节点包含数据和指向下...

    Python Queue模块详细介绍及实例

    Python的`Queue`模块是多线程编程中用于线程间通信的重要工具,它提供了队列数据结构的实现,确保了线程安全的数据交换。队列是一种先进先出(FIFO)的数据结构,即最早放入队列的元素最早被取出。`Queue`模块提供了...

    python 队列Queue的使用 python2例程展示了队列Queue的使用过程,供学习参考使用

    Python中的`queue`模块提供了多种类型的队列,包括`Queue`(默认限制大小)、`LifoQueue`(后进先出,类似堆栈)和`PriorityQueue`(优先级队列)。这些队列都实现了线程安全的`put()`和`get()`方法,用于添加和获取...

    python模块

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

    基于python的Queue-Basic-List.md

    `queue.Queue`是Python标准库中用于实现同步队列的标准模块。它主要用于多线程环境中,确保数据安全地在不同线程间传递。 - **构造函数**:`queue.Queue(maxsize=0)`,其中`maxsize`指定队列的最大大小,默认为0...

    python队列Queue的详解

    Python中的`Queue`模块提供了线程安全的队列实现,这对于多线程环境下的数据同步和通信至关重要。队列是一种先进先出(FIFO)的数据结构,它遵循“先入先出”的原则,即最早放入队列的元素最早被取出。`Queue`模块...

    Python Queue模块详解

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

    python标准库 中文

    6. **并发和多线程**:threading模块支持多线程编程,queue模块提供了线程安全的数据结构,用于线程间通信。 7. **日期和时间**:datetime模块提供了日期、时间和时区的处理,time模块则提供时间相关的函数。 8. *...

    Python:pygame飞机大战源码和素材

    此外,游戏可能还需要声音效果和背景音乐,Pygame的`pygame.mixer`模块可以用来播放和管理这些音频素材。 5. **游戏逻辑** - **飞机移动**:根据用户输入,更新飞机的位置。 - **子弹发射**:玩家按下射击键时,...

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

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

    Python进程Process模块-Python零基础入门教程.pdf

    【Python进程Process模块】是Python中用于处理进程的模块,它是多进程编程的基础。在操作系统中,进程是对各种资源管理的单位,包括内存、网络接口等。一个进程可以包含多个子进程,每个进程都有自己的独立内存空间...

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

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

    Spider_Python:Python爬虫之多进程

    首先导入`multiprocessing`模块: ```python from multiprocessing import Process ``` 然后,定义一个函数作为子进程要执行的任务,并创建`Process`实例: ```python def spider(url): # 在这里编写爬虫逻辑,...

    python使用Queue在多个子进程间交换数据的方法

    Python的`multiprocessing`模块提供了解决方案,其中`Queue`类允许我们在多个子进程中安全地交换数据。本篇文章将深入探讨如何使用`Queue`实现进程间的数据交互。 首先,让我们了解`multiprocessing`模块。它是...

Global site tag (gtag.js) - Google Analytics