18.5.8. 队列

Queues:

asyncio queue API was designed to be close to classes of the queue 模块 ( Queue , PriorityQueue , LifoQueue ), but it has no timeout parameter. The asyncio.wait_for() function can be used to cancel a task after a timeout.

18.5.8.1. 队列

class asyncio. 队列 ( maxsize=0 , * , loop=None )

A queue, useful for coordinating producer and consumer coroutines.

maxsize is less than or equal to zero, the queue size is infinite. If it is an integer greater than 0 ,那么 yield from put() will block when the queue reaches maxsize , until an item is removed by get() .

Unlike the standard library queue , you can reliably know this Queue’s size with qsize() , since your single-threaded asyncio application won’t be interrupted between calling qsize() and doing an operation on the Queue.

此类是 非线程安全 .

3.4.4 版改变: New join() and task_done() 方法。

empty ( )

返回 True 若队列为空, False 否则。

full ( )

返回 True 若有 maxsize 项在队列中。

注意

If the Queue was initialized with maxsize=0 (默认),那么 full() is never True .

协程 get ( )

Remove and return an item from the queue. If queue is empty, wait until an item is available.

此方法是 协程 .

另请参阅

The empty() 方法。

get_nowait ( )

从队列移除并返回项。

返回项若立即可用,否则引发 QueueEmpty .

协程 join ( )

Block 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.

此方法是 协程 .

3.4.4 版新增。

协程 put ( item )

Put an item into the queue. If the queue is full, wait until a free slot is available before adding item.

此方法是 协程 .

另请参阅

The full() 方法。

put_nowait ( item )

将项不阻塞放入队列。

若没有立即可用的空闲槽,引发 QueueFull .

qsize ( )

Number of items in the queue.

task_done ( )

Indicate that a formerly enqueued task is complete.

Used by queue consumers. For each get() 用于抓取任务,后续调用 task_done() tells the queue that the processing on the task is complete.

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

引发 ValueError if called more times than there were items placed in the queue.

3.4.4 版新增。

maxsize

队列中允许的项数。

18.5.8.2. PriorityQueue

class asyncio. PriorityQueue

子类化的 Queue ; retrieves entries in priority order (lowest first).

Entries are typically tuples of the form: (priority number, data).

18.5.8.3. LifoQueue

class asyncio. LifoQueue

子类化的 Queue that retrieves most recently added entries first.

18.5.8.3.1. JoinableQueue

class asyncio. JoinableQueue

Deprecated alias for Queue .

Deprecated since version 3.4.4.

18.5.8.3.2. Exceptions

exception asyncio. QueueEmpty

异常被引发当 get_nowait() method is called on a Queue 对象为空。

exception asyncio. QueueFull

异常被引发当 put_nowait() method is called on a Queue 对象已满。