"""Offline Kotlin 2.x semantic verifier for Chapter 37: Coroutines (asyncio model)."""
import asyncio
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
async def _run_structured_and_supervisor():
# 1. launch non-blocking ordering: main continues, B (5ms) finishes before A (20ms)
launch_log = []
async def job_a():
await asyncio.sleep(0.025)
launch_log.append("协程 A 完成")
async def job_b():
await asyncio.sleep(0.005)
launch_log.append("协程 B 完成")
t_a = asyncio.create_task(job_a())
t_b = asyncio.create_task(job_b())
launch_log.append("main 协程继续执行")
await asyncio.gather(t_a, t_b)
# 2. suspend chain
async def fetch_site() -> str:
await asyncio.sleep(0.005)
return "mbsky.cn"
site = await fetch_site()
# 3. structured coroutineScope: parent waits for all children, and failure cancels sibling
scope_log = []
sibling_cancelled = False
async def load_home_page():
async with asyncio.TaskGroup() as tg:
async def mod_a():
await asyncio.sleep(0.020)
scope_log.append("模块 A 加载完成")
async def mod_b():
await asyncio.sleep(0.005)
scope_log.append("模块 B 加载完成")
tg.create_task(mod_a())
tg.create_task(mod_b())
scope_log.append("等待所有子协程……")
scope_log.append("首页全部就绪")
await load_home_page()
try:
async with asyncio.TaskGroup() as tg:
async def failing_child():
await asyncio.sleep(0.005)
raise RuntimeError("child boom")
async def slow_sibling():
nonlocal sibling_cancelled
try:
await asyncio.sleep(0.5)
except asyncio.CancelledError:
sibling_cancelled = True
raise
tg.create_task(failing_child())
tg.create_task(slow_sibling())
except* RuntimeError:
pass
# 4. supervisorScope: sibling survives when one child fails
async def sup_fail():
await asyncio.sleep(0.005)
raise RuntimeError("isolated failure")
async def sup_ok():
await asyncio.sleep(0.015)
return "sibling_survived"
sup_results = await asyncio.gather(sup_fail(), sup_ok(), return_exceptions=True)
return {
"launch_order": launch_log,
"suspend_fetch": site,
"scope_order": scope_log,
"coroutineScope_cancels_sibling": sibling_cancelled,
"supervisorScope_sibling_result": sup_results[1],
"supervisorScope_failed_type": type(sup_results[0]).__name__,
}
def case_suspend_launch_and_structured_scope():
actual = asyncio.run(_run_structured_and_supervisor())
expected = {
"launch_order": ["main 协程继续执行", "协程 B 完成", "协程 A 完成"],
"suspend_fetch": "mbsky.cn",
"scope_order": ["等待所有子协程……", "模块 B 加载完成", "模块 A 加载完成", "首页全部就绪"],
"coroutineScope_cancels_sibling": True,
"supervisorScope_sibling_result": "sibling_survived",
"supervisorScope_failed_type": "RuntimeError",
}
return {
"name": "suspend_launch_and_structured_scope",
"summary": "Verify launch non-blocking order, suspend chain, coroutineScope cancellation, and supervisorScope isolation",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def _run_cancellation_and_timeout():
# Cooperative cancellation at suspension point (delay)
downloads = []
async def downloader():
for i in range(5):
await asyncio.sleep(0.012)
downloads.append(f"第 {i} 次下载……")
task = asyncio.create_task(downloader())
await asyncio.sleep(0.030)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# withTimeoutOrNull returns None on timeout
async def with_timeout_or_null(sec: float, coro):
try:
return await asyncio.wait_for(coro, timeout=sec)
except TimeoutError:
return None
timeout_res = await with_timeout_or_null(0.015, asyncio.sleep(0.5, result="下载完成"))
# Cooperative CPU loop using ensureActive() check
cancelled_flag = False
stopped_early = False
def ensure_active():
if cancelled_flag:
raise asyncio.CancelledError()
iterations = 0
try:
for i in range(1, 1000):
iterations = i
if i == 50:
cancelled_flag = True
if i % 10 == 0:
ensure_active()
except asyncio.CancelledError:
stopped_early = True
return {
"job_cancelled": task.cancelled(),
"stopped_before_all_5": len(downloads) < 5,
"timeout_or_null": timeout_res,
"ensure_active_stopped_at": iterations if stopped_early else -1,
}
def case_cancellation_timeout_and_ensure_active():
actual = asyncio.run(_run_cancellation_and_timeout())
expected = {
"job_cancelled": True,
"stopped_before_all_5": True,
"timeout_or_null": None,
"ensure_active_stopped_at": 50,
}
return {
"name": "cancellation_timeout_and_ensure_active",
"summary": "Verify cooperative job.cancel(), withTimeoutOrNull returning None, and ensureActive() in CPU loops",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def _run_async_await_and_channel():
async def load_module(name: str, delay_s: float) -> str:
await asyncio.sleep(delay_s)
return f"{name} 加载完成"
loop = asyncio.get_running_loop()
t0 = loop.time()
d_a = asyncio.create_task(load_module("模块 A", 0.035))
d_b = asyncio.create_task(load_module("模块 B", 0.035))
res_a = await d_a
res_b = await d_b
elapsed = loop.time() - t0
# Channel (bounded Queue) producer -> consumer
channel: asyncio.Queue[int | None] = asyncio.Queue(maxsize=2)
received = []
async def producer():
for x in (10, 20, 30):
await channel.put(x)
await channel.put(None)
async def consumer():
while True:
item = await channel.get()
if item is None:
break
received.append(item)
await asyncio.gather(producer(), consumer())
return {
"deferred_results": [res_a, res_b],
"ran_concurrently": elapsed < 0.065,
"channel_received": received,
}
def case_async_await_and_channel():
actual = asyncio.run(_run_async_await_and_channel())
expected = {
"deferred_results": ["模块 A 加载完成", "模块 B 加载完成"],
"ran_concurrently": True,
"channel_received": [10, 20, 30],
}
return {
"name": "async_await_and_channel",
"summary": "Verify parallel async/await Deferred execution and bounded Channel producer-consumer handoff",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def _run_cold_flow_and_exceptions():
# Cold Flow: each collector triggers a fresh execution of the async generator
executions = 0
async def number_flow():
nonlocal executions
executions += 1
for i in range(1, 6):
await asyncio.sleep(0)
yield i
async def flow_map(src, fn):
async for item in src:
yield fn(item)
async def flow_filter(src, pred):
async for item in src:
if pred(item):
yield item
transformed = [
x async for x in flow_filter(flow_map(number_flow(), lambda n: n * 10), lambda n: n > 20)
]
collected = [f"收到:{x}" async for x in number_flow()]
# Flow catch operator catches upstream error and emits fallback
async def risky_flow():
yield "第一项"
raise RuntimeError("数据源断开")
async def catch_flow(src):
try:
async for item in src:
yield item
except Exception as exc:
yield f"捕获到异常:{exc}"
recovered = [x async for x in catch_flow(risky_flow())]
# CoroutineExceptionHandler applies to uncaught root coroutines
handler_msgs = []
async def root_launch(coro, handler):
try:
await coro
except asyncio.CancelledError:
raise
except Exception as exc:
handler(exc)
async def failing_root():
raise RuntimeError("任务失败")
await root_launch(failing_root(), lambda e: handler_msgs.append(f"全局处理:{e}"))
return {
"cold_flow_executions": executions,
"transformed": transformed,
"collected": collected,
"risky_recovered": recovered,
"root_handler": handler_msgs,
}
def case_cold_flow_and_exceptions():
actual = asyncio.run(_run_cold_flow_and_exceptions())
expected = {
"cold_flow_executions": 2,
"transformed": [30, 40, 50],
"collected": ["收到:1", "收到:2", "收到:3", "收到:4", "收到:5"],
"risky_recovered": ["第一项", "捕获到异常:数据源断开"],
"root_handler": ["全局处理:任务失败"],
}
return {
"name": "cold_flow_and_exceptions",
"summary": "Verify cold Flow re-execution, map/filter/catch operators, and root CoroutineExceptionHandler",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_suspend_launch_and_structured_scope(),
case_cancellation_timeout_and_ensure_active(),
case_async_await_and_channel(),
case_cold_flow_and_exceptions(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
入口文件:projects/kotlin-coroutines-lab/explore-coroutines.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-coroutines.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2140.zip