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

运行离线 Python 校验:async/await 非阻塞挂起、async let/TaskGroup、协作式取消超时与 @MainActor

PYTHONWindows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。explore-concurrency.py
explore-concurrency.py210 行
"""Offline CPython 3.12.14 semantic verifier for Swift Structured Concurrency (CH41)."""
import asyncio
import json


class FetchError(Exception):
    def __init__(self, kind: str, detail=None) -> None:
        super().__init__(kind)
        self.kind = kind
        self.detail = detail


async def fetch_page(name: str, delay_ms: int = 2) -> str:
    await asyncio.sleep(delay_ms / 1000.0)
    return f"{name} 内容"


async def fetch_score(uid: int) -> int:
    await asyncio.sleep(0.002)
    if uid <= 0:
        raise FetchError("badStatus", uid)
    return uid * 10


async def run_case_async_await_and_throws():
    home = await fetch_page("首页")
    doc = await fetch_page("Swift 教程")
    ok_score = await fetch_score(7)
    err_msg = ""
    try:
        await fetch_score(-1)
    except FetchError as e:
        err_msg = f"出错:{e.kind}({e.detail})"

    actual = {"pages": [home, doc], "score_ok": ok_score, "error": err_msg}
    expected = {
        "pages": ["首页 内容", "Swift 教程 内容"],
        "score_ok": 70,
        "error": "出错:badStatus(-1)",
    }
    return {
        "name": "async_await_and_async_throws",
        "summary": "Verify sequential async/await suspension and try await error handling in async throws functions.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


async def run_case_task_async_let_and_group():
    # Unstructured Task handles awaited in fixed order
    t1 = asyncio.create_task(fetch_page("任务甲"))
    t2 = asyncio.create_task(fetch_page("任务乙"))
    task_results = [await t1, await t2]

    # Structured async let pair
    pair = list(await asyncio.gather(fetch_page("async let 甲"), fetch_page("async let 乙")))

    # Dynamic TaskGroup
    async def group_worker(i: int) -> int:
        await asyncio.sleep((5 - i) * 0.001)
        return i * 100

    group_results: list[int] = []
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(group_worker(i)) for i in range(1, 5)]
    group_results = sorted(t.result() for t in tasks)

    actual = {
        "task_results": task_results,
        "async_let_pair": pair,
        "task_group_sorted": group_results,
    }
    expected = {
        "task_results": ["任务甲 内容", "任务乙 内容"],
        "async_let_pair": ["async let 甲 内容", "async let 乙 内容"],
        "task_group_sorted": [100, 200, 300, 400],
    }
    return {
        "name": "task_async_let_and_task_group",
        "summary": "Verify Task handles, structured async let concurrent binding, and dynamic TaskGroup result sorting.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


async def run_case_cancellation_and_timeout():
    async def step(n: int) -> int:
        await asyncio.sleep(0.5)
        return n * n

    job = asyncio.create_task(step(4))
    await asyncio.sleep(0)
    job.cancel()
    cancelled_caught = False
    try:
        await job
    except asyncio.CancelledError:
        cancelled_caught = True

    # Cooperative loop checking cancellation flag
    cancel_flag = {"cancelled": False}
    total = 0
    for i in range(1, 100):
        if i == 11:
            cancel_flag["cancelled"] = True
        if cancel_flag["cancelled"]:
            break
        total += i

    async def with_timeout(seconds: float, coro):
        try:
            return await asyncio.wait_for(coro, timeout=seconds)
        except asyncio.TimeoutError as exc:
            raise FetchError("timedOut") from exc

    async def fast_op():
        await asyncio.sleep(0.005)
        return "快速返回"

    async def slow_op():
        await asyncio.sleep(0.5)
        return "永远不会返回"

    fast_res = await with_timeout(0.2, fast_op())
    timeout_err = ""
    try:
        await with_timeout(0.02, slow_op())
    except FetchError as e:
        timeout_err = f"超时:{e.kind}"

    actual = {
        "job_cancelled": cancelled_caught,
        "cooperative_loop_sum": total,
        "fast_result": fast_res,
        "slow_timeout": timeout_err,
    }
    expected = {
        "job_cancelled": True,
        "cooperative_loop_sum": 55,
        "fast_result": "快速返回",
        "slow_timeout": "超时:timedOut",
    }
    return {
        "name": "cooperative_cancellation_and_timeout",
        "summary": "Verify cooperative task cancellation (CancellationError & isCancelled) and racing timeout helper.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


async def run_case_main_actor():
    executor_log: list[tuple[str, str]] = []
    main_lock = asyncio.Lock()

    async def run_on_main_actor(fn):
        async with main_lock:
            return fn("MainActor")

    class ViewModel:
        def __init__(self) -> None:
            self.title = "加载中"

        def refresh(self, executor: str) -> str:
            self.title = "页面已加载"
            executor_log.append((executor, self.title))
            return self.title

    await run_on_main_actor(lambda ex: executor_log.append((ex, "主线程更新界面:首页加载完成")))
    vm = await run_on_main_actor(lambda _: ViewModel())
    await run_on_main_actor(vm.refresh)

    actual = {
        "all_on_main_actor": all(ex == "MainActor" for ex, _ in executor_log),
        "messages": [msg for _, msg in executor_log],
    }
    expected = {
        "all_on_main_actor": True,
        "messages": ["主线程更新界面:首页加载完成", "页面已加载"],
    }
    return {
        "name": "main_actor_isolation_dispatch",
        "summary": "Verify @MainActor hops execution onto the MainActor executor for UI function and ViewModel mutations.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


async def run_all() -> dict:
    return {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            await run_case_async_await_and_throws(),
            await run_case_task_async_let_and_group(),
            await run_case_cancellation_and_timeout(),
            await run_case_main_actor(),
        ],
    }


def main() -> None:
    print(json.dumps(asyncio.run(run_all()), ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

入口文件:projects/swift-concurrency-lab/explore-concurrency.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-concurrency.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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