queue
— 同步队列类
¶
源代码: Lib/queue.py
The
queue
模块实现多生产者、多消费者队列。在线程化编程中尤其有用,当必须在多个线程之间安全交换信息时。
Queue
类在此模块中实现所有要求的锁定语义。
模块实现了 3 种队列类型,唯一不同之处是检索条目的次序。在
FIFO
队列, 首先检索最先添加的任务。在
LIFO
队列,首先检索最近添加的条目 (操作像堆栈)。采用优先级队列,条目保持排序 (使用
heapq
模块) 且首先检索最低值条目。
在内部,这 3 种队列类型使用锁,以临时阻塞竞争线程;不管怎样,它们并不是为处理线程内的重入而设计的。
此外,模块实现简单
FIFO
队列类型,
SimpleQueue
,具体实现提供额外保证,以换取更小功能。
The
queue
模块定义下列类和异常:
- class 队列。 队列 ( maxsize = 0 ) ¶
-
构造函数为 FIFO 队列。 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 <= 0,队列大小无限。
- class 队列。 LifoQueue ( maxsize = 0 ) ¶
-
构造函数为 LIFO 队列。 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 <= 0,队列大小无限。
- class 队列。 PriorityQueue ( maxsize = 0 ) ¶
-
优先级队列构造函数。 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 <= 0,队列大小无限。
The lowest valued entries are retrieved first (the lowest valued entry is the one that would be returned by
min(entries)). A typical pattern for entries is a tuple in the form:(priority_number, data).若 data elements are not comparable, the data can be wrapped in a class that ignores the data item and only compares the priority number:
from dataclasses import dataclass, field from typing import Any @dataclass(order=True) class PrioritizedItem: priority: int item: Any=field(compare=False)