Swift 并发编程:async 与 await
系统核对 Swift 5.5+ 结构化并发模型:async/await 非阻塞挂起语义、async throws 组合、Task/async let/TaskGroup 并发编排、协作式取消与超时控制、@MainActor 主线程隔离及常见疑问。
学完这一章,你能够
- 系统核对 Swift 5.5+ 结构化并发模型:async/await 非阻塞挂起语义、async throws 组合、Task/async let/TaskGroup 并发编排、协作式取消与超时控制、@MainActor 主线程隔离及常见疑问。
并发问题背景与 async / await 非阻塞挂起
传统回调嵌套(completion handler)容易导致“金字塔地狱”、错误处理遗漏与控制流割裂,而盲目开启大量线程又会造成上下文切换与内存开销。Swift 5.5 引入的原生结构化并发以 `async`/`await`、`Task`、`TaskGroup` 与隔离执行器为核心,用接近同步代码的自上而下写法表达异步流程,同时由语言和运行时负责协作式调度与生命周期收敛。
在函数参数列表后标注 `async` 即声明异步函数,调用点必须写 `await` 显式标出潜在挂起点(suspension point)。遇到 `await` 时,当前任务会保存续体并把底层线程让渡给并发线程池中的其他就绪任务,绝不会像 `sleep` 那样阻塞线程;待 I/O 或子任务完成后,运行环境再从挂起点恢复执行(恢复时未必仍在原来的物理线程上,除非受 `@MainActor` 等特定执行器约束)。若异步操作同时可能失败,可将关键字按固定顺序写为 `async throws`,调用点则组合为 `try await` 配合 `do-catch` 捕获。离线校验器基于 Python `asyncio` 验证了 `async`/`await` 非阻塞挂起与 `async throws` 异常传播。
Task、async let 与 TaskGroup 结构化并发
从同步上下文(如按钮点击或同步函数)启动异步代码时,可使用 `Task { ... }` 创建顶层非结构化任务;它默认继承当前 actor 上下文与优先级,并返回可读取 `.value` 或调用 `.cancel()` 的任务句柄。相比之下,结构化并发要求子任务的生命周期严格限定在父作用域之内,退出作用域前必须全部完成或被自动取消,避免遗留孤儿任务。
当并发分支数量在编译期固定时(例如同时拉取用户信息、订单列表与推荐商品),使用 `async let` 绑定即可立即并行启动多个异步表达式,并在后续需要结果处再统一 `await`,总耗时近似最慢分支而非串行累加。当并发任务数量需在运行时动态决定(例如遍历长度不定的 URL 数组)时,使用 `withTaskGroup` 或 `withThrowingTaskGroup` 动态 `group.addTask { ... }` 并以 `for await` 收集结果;由于子任务完成顺序具有不确定性,若需保留原始顺序应附带索引并在收集后重排。离线校验器已实测 `async let` 并行提速与 `TaskGroup` 动态扇出汇总。
协作式取消、超时控制、@MainActor 与常见问题
Swift 并发采用协作式取消(cooperative cancellation):调用 `task.cancel()` 或 `group.cancelAll()` 只会为任务树打上取消标记,并不会粗暴杀死正在执行的线程。任务内部需要在合适检查点主动读取 `Task.isCancelled` 清理收尾,或调用 `try Task.checkCancellation()` 立即抛出 `CancellationError`。结合 `withThrowingTaskGroup` 同时运行目标工作任务与睡眠超时任务,待先完成者返回后立刻执行 `group.cancelAll()`,即可实现干净的超时控制(如超过时限抛出超时错误并中止慢任务)。
UI 框架(UIKit/AppKit/SwiftUI)要求界面更新必须在主线程执行;将视图模型、类型或方法标注 `@MainActor` 后,编译器静态保证相关访问切回主执行器,必要时亦可借助 `await MainActor.run { ... }` 显式切换。常见问题解答:`await` 只挂起任务而不阻塞线程;非 `@MainActor` 的异步函数通常由全局协作线程池执行;固定少量并行优先 `async let`,动态数量用 `TaskGroup`,仅在需从同步边界脱离作用域启动时使用 `Task`;并发任务受调度影响完成顺序本就不可假定;`TaskGroup` 内子任务不能直接竞争修改外部可变局部变量,应通过返回值汇总到父任务;`async` 函数只能在异步上下文或 `Task` 中以 `await` 调用,不能当作普通同步函数直接执行。
Swift 结构化并发核心概念速查
| 概念 | 写法 | 作用 |
| 异步函数 | func fetch() async throws -> Data | 声明可能挂起且可抛出错误的异步操作。 |
| 等待 | let data = try await fetch() | 显式标记挂起点,挂起任务同时释放底层线程。 |
| 任务 | Task { await work() } | 在同步上下文创建异步执行单元并返回可控句柄。 |
| 任务组 | withTaskGroup / withThrowingTaskGroup | 在作用域内动态创建并汇聚可变数量的并发子任务。 |
| 执行器隔离 | @MainActor / actor | 约束状态与代码在指定执行器或主线程串行运行。 |
协作式取消核心 API 对照
| API | 作用 | 典型场景 |
| task.cancel() | 向指定任务及其子任务树传递取消信号。 | 用户取消请求或页面销毁时中止后台任务。 |
| Task.isCancelled | 返回布尔值,非抛错方式查询当前任务是否已被取消。 | 长循环内优雅收尾、释放资源或返回部分结果。 |
| Task.checkCancellation() | 若当前任务已取消则立即抛出 CancellationError。 | 支持 throws 的异步步骤中快速短路退出。 |
| group.cancelAll() | 取消当前 TaskGroup 内所有仍在运行的子任务。 | 竞态超时或首个有效结果到达后立即清理其余分支。 |
运行离线 Python 校验:async/await 非阻塞挂起、async let/TaskGroup、协作式取消超时与 @MainActor
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不会。Swift 采用协作式取消,task.cancel() 仅设置取消标志位;循环内部必须主动检查 Task.isCancelled 或调用 try Task.checkCancellation(),任务才会响应取消并有序退出。