蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python queue:线程间传递任务与确认完成

实际比较先进先出、后进先出与优先级顺序,并验证队列满、空、超时和消费者停止。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

按访问顺序和容量选择队列

queue 为线程间传递提供同步队列。Queue 按先进先出取任务,LifoQueue 先取最近放入的元素,PriorityQueue 按值从小到大取。前三类的 maxsize 大于 0 时限制容量,设为 0 或负值时不设容量上限。进程间通信有 multiprocessing.Queue。

SimpleQueue 自 3.7 提供无容量上限的 FIFO。它支持 put、get、非阻塞变体、qsize 和 empty。其 put 忽略 block 和 timeout,get 仍可等待或超时。它没有 full、task_done 和 join。

线程安全针对各次队列操作。读共享对象后的修改、先检查再读写等复合操作仍要设计同步。Queue、LifoQueue、PriorityQueue 的锁不支持同一线程重入。CPython 的 SimpleQueue 有单独的重入条件,详见对应实现文档。

显式处理满、空和等待

put 把任务放入队列,通常返回 None。达到容量限制时,默认等待空位。给正的 timeout 可限制等待,超时抛 Full。put_nowait 等价于 put(item, block=False),满时立即抛 Full。

get 移除并返回一项,空时默认等待。有超时仍无元素时抛 Empty。get_nowait 等价于 get(block=False),应处理 Empty。block=False 时忽略 timeout。阻塞调用通常不使用负超时,实验在有界队列上验证 ValueError。

qsize、empty 和 full 是瞬时观测值。实验先读到队列中有一项,另一个线程随后将其取走,下一次 get_nowait 得到 Empty。用 get 或 put 的实际结果做分支,避免把快照当作下一次操作的保证。

给优先级相同的任务指定顺序

PriorityQueue 常用 (优先级, 数据) 元组,数值较小的优先。第一项相等时会继续比较数据。两个同优先级的字符串会按字符串顺序,不能假定沿用入队次序。两个字典不能直接比较,实验单独捕获 TypeError。

为同一生产入口生成递增序号,可用 (优先级, 序号, 数据),使并列项按序号取出而无需比较数据。多个生产者若共用序号,应按运行环境设计同步或先集中分派唯一序号。

确认完成与停止消费者

每次 put 都增加一项未完成任务,get 只取出数据,task_done 才确认处理结束。join 等待未完成数归零,即使队列已经空也可能继续等待。多调一次 task_done 会报 ValueError。

有界队列给生产者施加背压。实验让容量为 3 的队列同时接收普通任务、None 和一项故意失败的任务。消费者在 finally 中对每次 get 确认一次,失败结果单独记录。生产完毕后为每个消费者放一个唯一哨兵,哨兵也要确认。最后等待工作线程退出和任务确认都完成。

CPython 3.12 可用哨兵控制退出。3.13 起 Queue 增加 shutdown() 和 ShutDown。默认停止新增后可排空现有任务,immediate=True 会丢弃待处理项,join 返回时可能有工作未做。本次运行用 3.12 核验哨兵和完成确认,3.13 行为按官方文档单列。

解压本站 ZIP 后运行 python python-queue.py,查看顺序、异常和线程清理的实际输出。线程的到达顺序由同步条件约束,实验不要求不同消费者拿到固定的任务编号。

下载本站 queue 实验 ZIP

所需环境:CPython 3.12 标准库

ZIP SHA256:836c76ab87b27f47c0c0d88f3beee0d3aa60c92e444d2808f3b43f452c694a86

队列类型

类、方法或参数作用和条件
queue.Queue(maxsize=0)先进先出,支持容量控制与任务跟踪。
queue.LifoQueue(maxsize=0)后进先出,最后加入的项最先取出。
queue.PriorityQueue(maxsize=0)最小值先出。并列时需考虑后续字段可比较性。
queue.SimpleQueue()自 3.7 提供的无容量上限 FIFO,省略任务跟踪。

操作和完成确认

类、方法或参数作用和条件
put(item, block=True, timeout=None)放入任务,返回 None。Queue 满时可等待或抛 Full,SimpleQueue.put 无容量等待。
get(block=True, timeout=None)移除并返回任务。空时等待或抛 Empty。
empty()返回此刻是否为空。跨线程不能保证下一次 get 会成功。
full()Queue 等返回是否达到容量。SimpleQueue 无此接口。
qsize()返回近似长度,其他线程可随即修改。
task_done()Queue 等确认一次任务完成,返回 None。多调会抛 ValueError。SimpleQueue 无此接口。
join()Queue 等等待未完成任务数归零并返回 None。SimpleQueue 无此接口。

阻塞配置

类、方法或参数作用和条件
block通常默认 True,False 立即尝试。SimpleQueue.put 忽略此参数。
timeout默认 None。阻塞调用可给秒数,满或空持续至超时会抛 Full 或 Empty。非阻塞时忽略。

本章自编源码与运行范围

Python · 阅读源码
"""Observe queue ordering, backpressure, and worker completion."""

import itertools
import json
import queue
import sys
import threading


WAIT = 3


def observe():
    checks = []

    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        checks.append(dict(name=name, input=inputs, operation=operation, actual=actual,
                           expected=expected, passed=True))

    def rejects(name, error_type, inputs, operation, call):
        try:
            call()
        except error_type as exc:
            check(name, type(exc).__name__, error_type.__name__, inputs, operation)
        else:
            raise AssertionError(name)

    values = ["north", "east", "south"]
    for cls, expected in ((queue.Queue, values), (queue.LifoQueue, values[::-1]),
                          (queue.SimpleQueue, values)):
        work = cls()
        outputs = [work.put(value) for value in values]
        check(cls.__name__ + " order and put return",
              [[work.get_nowait() for _ in values], outputs], [expected, [None, None, None]], values,
              "Enqueue three values and read them back without waiting")
    unbounded = queue.Queue(maxsize=0)
    for number in range(5):
        unbounded.put_nowait(number)
    check("nonpositive maxsize is unbounded", [unbounded.qsize(), unbounded.full()], [5, False],
          "maxsize=0", "Enqueue five values and observe no full state")

    work = queue.PriorityQueue()
    for item in [(4, "archive"), (0, "alarm"), (2, "check")]:
        work.put(item)
    check("priority tuple smallest first", [work.get_nowait()[1] for _ in range(3)],
          ["alarm", "check", "archive"], "priorities 4, 0, 2", "Read according to numeric priority")
    for item in [(3, "west"), (3, "east")]:
        work.put(item)
    check("equal priority compares next tuple field", [work.get_nowait()[1] for _ in range(2)],
          ["east", "west"], "two priority-3 string payloads", "Observe lexicographic order at a tie")
    sequence = itertools.count()
    for payload in [{"zone": "west"}, {"zone": "east"}]:
        work.put((3, next(sequence), payload))
    check("tie sequence preserves insertion without comparing payload",
          [work.get_nowait()[2]["zone"] for _ in range(2)], ["west", "east"],
          "two dictionaries with same priority", "Order by priority and unique sequence before the payload")
    ambiguous = queue.PriorityQueue()
    ambiguous.put((3, {"zone": "west"}))
    rejects("unorderable tied payload raises", TypeError, "equal priority with dictionaries and no tie key",
            "Insert into a disposable heap and discard it after the error",
            lambda: ambiguous.put((3, {"zone": "east"})))

    simple = queue.SimpleQueue()
    check("SimpleQueue put ignores block and timeout", simple.put("sealed", block=False, timeout=-1), None,
          "block=False, timeout=-1", "Put one value into unbounded SimpleQueue")
    check("SimpleQueue snapshot and get", [simple.qsize(), simple.empty(), simple.get(), simple.empty()],
          [1, False, "sealed", True], "one queued item", "Observe size and empty only without competing threads")
    check("SimpleQueue omits task tracking and full",
          [hasattr(simple, name) for name in ("full", "task_done", "join")], [False, False, False],
          "SimpleQueue", "Inspect availability of the three APIs")
    rejects("SimpleQueue timed get raises Empty", queue.Empty, "empty SimpleQueue with 0.03s timeout",
            "Perform a bounded blocking get", lambda: simple.get(timeout=0.03))

    snapshot = queue.Queue(maxsize=1)
    snapshot.put("seen")
    first_view = [snapshot.qsize(), snapshot.empty(), snapshot.full()]

    def drain_snapshot():
        snapshot.get_nowait()
        snapshot.task_done()

    other = threading.Thread(target=drain_snapshot, daemon=True)
    other.start()
    other.join(WAIT)
    check("another thread invalidates previous size and capacity snapshot",
          [first_view, [snapshot.qsize(), snapshot.empty(), snapshot.full()], other.is_alive()],
          [[1, False, True], [0, True, False], False], "one item observed before a competing consumer",
          "Inspect, let the second thread drain the queue, then inspect again")
    rejects("stale not-empty snapshot cannot authorize get", queue.Empty, "snapshot was nonempty before competing get",
            "Call get_nowait after competing thread completed", snapshot.get_nowait)

    bounded = queue.Queue(maxsize=1)
    check("empty snapshot", [bounded.qsize(), bounded.empty(), bounded.full()], [0, True, False],
          "empty bounded Queue", "Inspect instantaneous state")
    rejects("empty get_nowait raises", queue.Empty, "empty bounded Queue",
            "Call get_nowait", bounded.get_nowait)
    rejects("empty get block false raises", queue.Empty, "block=False",
            "Call get without waiting", lambda: bounded.get(block=False, timeout=WAIT))
    rejects("empty timed get raises", queue.Empty, "empty Queue with 0.03s timeout",
            "Call get with bounded waiting", lambda: bounded.get(timeout=0.03))
    rejects("negative blocking get timeout raises", ValueError, "timeout=-1 with block=True",
            "Call get with invalid timeout", lambda: bounded.get(timeout=-1))
    bounded.put("first")
    check("full snapshot", [bounded.qsize(), bounded.empty(), bounded.full()], [1, False, True],
          "maxsize=1 with one item", "Inspect instantaneous state")
    rejects("full put_nowait raises", queue.Full, "full Queue",
            "Call put_nowait", lambda: bounded.put_nowait("second"))
    rejects("full put block false raises", queue.Full, "block=False",
            "Call put without waiting", lambda: bounded.put("second", block=False, timeout=WAIT))
    rejects("full timed put raises", queue.Full, "full Queue with 0.03s timeout",
            "Call put with bounded waiting", lambda: bounded.put("second", timeout=0.03))
    rejects("negative blocking put timeout raises", ValueError, "timeout=-1 with block=True",
            "Call put with invalid timeout", lambda: bounded.put("second", timeout=-1))

    entered = threading.Event()
    finished = threading.Event()

    def producer():
        entered.set()
        bounded.put("second", timeout=WAIT)
        finished.set()

    worker = threading.Thread(target=producer, daemon=True)
    worker.start()
    if not entered.wait(WAIT):
        raise RuntimeError("producer did not start")
    blocked = not finished.wait(0.03)
    first = bounded.get(timeout=WAIT)
    bounded.task_done()
    worker.join(WAIT)
    second = bounded.get(timeout=WAIT)
    bounded.task_done()
    check("blocked producer resumes when space is freed", [blocked, finished.is_set(), worker.is_alive(), first, second],
          [True, True, False, "first", "second"], "full Queue and second producer",
          "Observe full interval, remove first item, and wait for producer")
    bounded.join()

    observation = threading.Event()
    consumed = queue.SimpleQueue()

    def wait_for_item():
        observation.set()
        consumed.put(bounded.get(timeout=WAIT))
        bounded.task_done()

    consumer = threading.Thread(target=wait_for_item, daemon=True)
    consumer.start()
    if not observation.wait(WAIT):
        raise RuntimeError("consumer did not start")
    pending = consumed.empty()
    bounded.put("arrived", timeout=WAIT)
    consumer.join(WAIT)
    check("waiting consumer resumes when data is published", [pending, consumed.get(timeout=WAIT), consumer.is_alive()],
          [True, "arrived", False], "empty Queue and waiting consumer", "Supply one value after the consumer starts")
    bounded.join()

    bounded.put("in-flight")
    item = bounded.get()
    ready = threading.Event()
    joined = threading.Event()

    def join_queue():
        ready.set()
        bounded.join()
        joined.set()

    waiter = threading.Thread(target=join_queue, daemon=True)
    waiter.start()
    if not ready.wait(WAIT):
        raise RuntimeError("join worker did not start")
    waiting = not joined.wait(0.03)
    empty = bounded.empty()
    done = bounded.task_done()
    waiter.join(WAIT)
    check("join waits for task_done even after get empties the queue",
          [item, empty, waiting, done, joined.is_set(), waiter.is_alive()],
          ["in-flight", True, True, None, True, False], "one task removed but unfinished",
          "Observe empty buffer, acknowledge once, and check that join resumes")
    rejects("extra task_done raises", ValueError, "all work already acknowledged",
            "Attempt to acknowledge one extra task", bounded.task_done)
    check("join returns None when all work is acknowledged", bounded.join(), None,
          "no pending tasks", "Call join on the completed queue")

    work = queue.Queue(maxsize=3)
    stop = object()
    results = queue.SimpleQueue()

    def consume():
        while True:
            task = work.get(timeout=WAIT)
            try:
                if task is stop:
                    return
                if task == "broken":
                    raise ValueError("demonstration error")
                results.put([task, "processed"])
            except ValueError:
                results.put([task, "rejected"])
            finally:
                work.task_done()

    workers = [threading.Thread(target=consume, daemon=True) for _ in range(2)]
    for thread in workers:
        thread.start()
    tasks = [None, "report", "broken", "alert", "index"]

    def produce():
        for task in tasks:
            work.put(task, timeout=WAIT)
        for _ in workers:
            work.put(stop, timeout=WAIT)

    source = threading.Thread(target=produce, daemon=True)
    source.start()
    source.join(WAIT)
    for thread in workers:
        thread.join(WAIT)
    if source.is_alive() or any(thread.is_alive() for thread in workers):
        raise RuntimeError("a worker did not finish")
    joiner = threading.Thread(target=work.join, daemon=True)
    joiner.start()
    joiner.join(WAIT)
    actual = sorted((results.get(timeout=WAIT) for _ in tasks), key=lambda row: str(row[0]))
    check("bounded workers acknowledge failures and each sentinel",
          [actual, joiner.is_alive(), work.empty(), results.empty()],
          [[[None, "processed"], ["alert", "processed"], ["broken", "rejected"], ["index", "processed"],
            ["report", "processed"]], False, True, True], "five tasks including None, one error, two unique sentinels",
          "Run producer and two consumers, collect each result, and wait for every acknowledgment")

    has_shutdown = sys.version_info >= (3, 13)
    check("shutdown API is version dependent", [hasattr(queue.Queue, "shutdown"), hasattr(queue, "ShutDown")],
          [has_shutdown, has_shutdown], "current interpreter", "Check the version-specific API without calling it")
    return checks


if __name__ == "__main__":
    print(json.dumps(observe(), ensure_ascii=True, indent=2))
运行本章核心实例

所需环境:Real queue ordering, contention, backpressure and task tracking in Windows CPython

当前源码 SHA256:a00bea1fbcab399495ff12844c49f8696db3fb49119340d506107a31cfb4c936

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据