蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHONReal queue ordering, contention, backpressure and task tracking in Windows CPythonpython-queue.py
python-queue.py240 行
"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Real queue ordering, contention, backpressure and task tracking in Windows CPython

入口文件:projects/python-lab/python-queue.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-queue.py,或下载右侧课程工程包。
  2. 确认本地已准备 Real queue ordering, contention, backpressure and task tracking in Windows CPython。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a298.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习