18.5.8. 队列集¶
Queues:
asyncio queue API was designed to be close to classes of the queue
module (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.
Queue
(maxsize=0, *, loop=None)¶ A queue, useful for coordinating producer and consumer coroutines.
If maxsize is less than or equal to zero, the queue size is infinite. If it is an integer greater than
0
, thenyield from put()
will block when the queue reaches maxsize, until an item is removed byget()
.Unlike the standard library
queue
, you can reliably know this Queue’s size withqsize()
, since your single-threaded asyncio application won’t be interrupted between callingqsize()
and doing an operation on the Queue.这个类不是线程安全的(not thread safe)。
3.4.4 版更變: New
join()
andtask_done()
methods.-
empty
()¶ 如果队列为空返回
True
,否则返回False
。
-
full
()¶ 如果有
maxsize
个条目在队列中,则返回True
。備註
If the Queue was initialized with
maxsize=0
(the default), thenfull()
is neverTrue
.
-
coroutine
get
()¶ 从队列中删除并返回一个元素。如果队列为空,则等待,直到队列中有元素。
This method is a coroutine.
也參考
The
empty()
method.
-
get_nowait
()¶ Remove and return an item from the queue.
立即返回一个队列中的元素,如果队列内有值,否则引发异常
QueueEmpty
。
-
coroutine
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.This method is a coroutine.
3.4.4 版新加入.
-
coroutine
put
(item)¶ Put an item into the queue. If the queue is full, wait until a free slot is available before adding item.
This method is a coroutine.
也參考
The
full()
method.
-
qsize
()¶ Number of items in the queue.
-
task_done
()¶ 表明前面排队的任务已经完成,即get出来的元素相关操作已经完成。
由队列使用者控制。每个
get()
用于获取一个任务,任务最后调用task_done()
告诉队列,这个任务已经完成。如果
join()
当前正在阻塞,在所有条目都被处理后,将解除阻塞(意味着每个put()
进队列的条目的task_done()
都被收到)。如果被调用的次数多于放入队列中的项目数量,将引发
ValueError
。3.4.4 版新加入.
-
maxsize
¶ 队列中可存放的元素数量。
-
18.5.8.2. PriorityQueue¶
18.5.8.3. LifoQueue¶
18.5.8.3.1. 异常¶
-
exception
asyncio.
QueueEmpty
¶ Exception raised when the
get_nowait()
method is called on aQueue
object which is empty.
-
exception
asyncio.
QueueFull
¶ Exception raised when the
put_nowait()
method is called on aQueue
object which is full.