python异步、多线程与多进程-来自元宝
Python 并发编程完全指南:异步、多线程与多进程(入门 → 进阶 → 高阶 → 实战)
本文系统讲解 Python 中三大并发模型:asyncio 异步编程、threading 多线程、multiprocessing 多进程。
采用中英混合讲解,关键术语保留英文原词(GIL、event loop、coroutine、task、future、executor 等),便于后续查阅官方文档。
代码示例尽量自包含,复制即可运行(Python 3.10+ 推荐,部分特性需 3.11+)。
目录
第〇章:先搞清几个核心概念
在动手写代码前,必须先统一术语。这一章是所有后续内容的基础。
0.1 Concurrency vs Parallelism(并发 vs 并行)
这是最容易被混用的两个词:
- Concurrency(并发):指系统具备同时处理多个任务的能力结构,即多个任务在时间上交替推进。重点在于"结构",不要求物理上同时进行。
- Parallelism(并行):指多个任务在物理上同时执行(需要多核 CPU)。
一句话区分:并发是关于结构的,并行是关于执行的。
并发(单核也能做到):
Task A: ====....====....====
Task B: ....====....====....
时间线 → 交替推进,但同一时刻只有一个在跑
并行(需要多核):
Task A: ========
Task B: ========
时间线 → 同一时刻多个都在跑
0.2 Synchronous vs Asynchronous(同步 vs 异步)
- Synchronous(同步):调用发出后,调用者一直等待结果返回才继续。代码顺序执行,符合直觉。
- Asynchronous(异步):调用发出后立即返回,结果通过回调 / future / await 在未来某个时刻交付,期间调用者可以做别的事。
注意:异步 ≠ 并行 ≠ 多线程。单线程也能实现异步(asyncio 就是典型),多线程也可以是同步阻塞的。
0.3 Blocking vs Non-blocking(阻塞 vs 非阻塞)
- Blocking(阻塞):当前执行流被挂起,直到操作完成。
- Non-blocking(非阻塞):操作立即返回,即使数据还没就绪也会返回"未就绪"状态。
asyncio 的威力正来自于:把阻塞的 I/O 等待换成非阻塞的等待,让出执行权给 event loop 去跑别的 coroutine。
0.4 I/O-bound vs CPU-bound(两类负载)
这是选择并发模型的唯一最重要判据:
| 类型 | 特点 | 典型场景 | 适合的模型 |
|---|---|---|---|
| I/O-bound | 大量时间在等网络/磁盘/数据库响应,CPU 很闲 | 爬虫、Web 后端、文件读写 | asyncio(首选)、多线程 |
| CPU-bound | 大量计算,CPU 满载 | 图像处理、科学计算、数据压缩 | 多进程(绕过 GIL) |
⚠️ 判断口诀:"等得多"用异步/线程,"算得多"用进程。
0.5 GIL:Python 的全局解释器锁
GIL(Global Interpreter Lock) 是 CPython 解释器的一把互斥锁,保证同一时刻只有一个线程在执行 Python 字节码。
这带来两个关键结论:
- 多线程无法真正并行执行 CPU 密集型任务——它们只是快速切换,在多核上也跑不满。
- 但多线程对 I/O-bound 任务依然高效——因为 I/O 等待时会释放 GIL,其他线程可以运行。
而 multiprocessing 每个进程有独立的 GIL 和独立的内存空间,所以能真正利用多核做并行。代价是进程间通信(IPC)成本更高。
📌 扩展阅读:Python 3.13 引入了 "free-threaded"(无 GIL) 的实验性构建,但本文实战仍以主流带 GIL 版本为主,详见第 17 章。
入门篇:三大并发模型基础
本章目标是让你能跑起来,理解每个模型的"最小可用形态"。
1. threading 多线程入门
threading 模块是 Python 多线程的标准库。一个 Thread 代表一条执行流。
1.1 创建并启动线程
import threading
import time
def worker(name: str, delay: float) -> None:
"""线程要执行的任务。"""
print(f"[{threading.current_thread().name}] 开始工作: {name}")
time.sleep(delay) # 模拟 I/O 等待(会释放 GIL)
print(f"[{threading.current_thread().name}] 完成: {name}")
# 创建线程(不会立即运行)
t1 = threading.Thread(target=worker, args=("任务A", 1), name="Worker-1")
t2 = threading.Thread(target=worker, args=("任务B", 1.5), name="Worker-2")
# 启动线程
t1.start()
t2.start()
# join() 阻塞当前(主)线程,直到目标线程结束
t1.join()
t2.join()
print("所有线程执行完毕")
关键 API:
Thread(target=callable, args=(...)):创建线程.start():启动,交给操作系统调度.join():等待该线程结束.daemon = True:设为守护线程,主线程退出时它会被强制结束(不推荐依赖,资源可能来不及释放)
1.2 线程间共享变量与竞争条件
线程共享同一进程的内存,因此可以直接读写全局变量——这既是便利,也是灾难之源。
import threading
counter = 0
def unsafe_increment() -> None:
global counter
for _ in range(100_000):
counter += 1 # 这不是原子操作!实际是 load → add → store
threads = [threading.Thread(target=unsafe_increment) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(f"期望: 400000, 实际: {counter}") # 几乎必然小于 400000
为什么会错? counter += 1 在字节码层面是多条指令,线程可能在中间被切换,导致"读到的旧值被覆盖"。这就是 race condition(竞争条件)。
解决办法:用
Lock(见进阶篇第 5 章)。
1.3 通过继承 Thread 类
除了传 target,还可以子类化:
import threading
class MyThread(threading.Thread):
def __init__(self, name: str):
super().__init__(name=name)
self.result = None
def run(self): # 重写 run(),start() 会调用它
self.result = f"线程 {self.name} 的结果"
print(self.result)
t = MyThread("T1")
t.start()
t.join()
2. multiprocessing 多进程入门
multiprocessing 模块提供了与 threading 接口高度相似的 API,但每个 Process 是独立进程,拥有独立的内存空间。
2.1 创建并启动进程
import multiprocessing as mp
import os
import time
def cpu_task(n: int) -> None:
"""CPU 密集型任务。"""
print(f"[PID={os.getpid()}] 进程 {mp.current_process().name} 计算中...")
total = 0
for i in range(n):
total += i * i
print(f"[PID={os.getpid()}] 结果: {total}")
if __name__ == "__main__": # Windows 必须加这行保护!
processes = [
mp.Process(target=cpu_task, args=(5_000_000,), name=f"P{i}")
for i in range(4)
]
for p in processes: p.start()
for p in processes: p.join()
print("所有进程结束")
API 与 threading 几乎一致:Process、start()、join()、name。
🔑
if __name__ == "__main__":是 Windows 的硬性要求,因为 Windows 用 spawn 方式创建进程会重新导入模块,没有这行会无限递归。Linux/macOS 用 fork 相对宽松,但加上这行是跨平台的好习惯。
2.2 进程间不共享内存
import multiprocessing as mp
def modify(lst):
lst.append(100) # 修改的是副本!
if __name__ == "__main__":
data = [1, 2, 3]
p = mp.Process(target=modify, args=(data,))
p.start()
p.join()
print(data) # [1, 2, 3],没有被修改
进程之间默认不共享内存,传参是序列化和拷贝。要共享数据,需要用 Queue/Pipe/Manager/shared_memory(见进阶/高阶篇)。
3. asyncio 异步编程入门
asyncio 是 Python 官方的单线程异步 I/O 框架。它的核心是 event loop(事件循环) + coroutine(协程)。
3.1 第一个异步程序
import asyncio
import time
async def say_hi(delay: float, msg: str) -> None:
"""async 定义的是 coroutine function,调用它返回 coroutine object。"""
await asyncio.sleep(delay) # await 把执行权让给 event loop
print(msg)
async def main() -> None:
# 顺序执行:两个 await 会串行
await say_hi(1, "Hello")
await say_hi(1, "World")
# 总耗时约 2 秒
asyncio.run(main())
三个关键词:
async def:定义 coroutine functionawait:挂起当前 coroutine,让出执行权,等可等待对象(awaitable)完成asyncio.run(coro):创建 event loop,运行 coroutine 直到结束(Python 3.7+ 推荐入口)
3.2 并发运行多个协程:create_task
上面两个 await 是串行的(总耗时 2 秒)。要让它们并发,用 asyncio.create_task 包装成 Task:
import asyncio
async def say_hi(delay: float, msg: str) -> None:
await asyncio.sleep(delay)
print(msg)
async def main() -> None:
# 创建 task = 把 coroutine 交给 event loop 调度
task1 = asyncio.create_task(say_hi(1, "Hello"))
task2 = asyncio.create_task(say_hi(1, "World"))
# 此时两个 task 都已在运行(并发)
await task1
await task2
# 总耗时约 1 秒!
asyncio.run(main())
Task 是"已排期运行的 coroutine"。理解层级:
coroutine(协程) —— 一段可挂起可恢复的函数
↓ create_task()
Task —— 被 event loop 调度的"待办事项"
↓ await / gather
最终结果
3.3 同步代码 vs 异步代码直观对比
# 同步:依次等待,总耗时 = 1+2+3 = 6 秒
def sync_main():
time.sleep(1); print("A")
time.sleep(2); print("B")
time.sleep(3); print("C")
# 异步:并发等待,总耗时 ≈ 3 秒(取最慢的那个)
async def async_main():
await asyncio.gather(
asyncio.sleep(1), print("A") or asyncio.sleep(0),
asyncio.sleep(2), print("B") or asyncio.sleep(0),
asyncio.sleep(3), print("C") or asyncio.sleep(0),
)
4. 三大模型选型对照
| 维度 | threading | multiprocessing | asyncio |
|---|---|---|---|
| 执行单位 | 线程(共享内存) | 进程(独立内存) | 协程(单线程内) |
| 并行能力 | 受 GIL 限制,I/O 有效 | 真正并行,多核可用 | 单线程,并发非并行 |
| 切换开销 | 较小 | 大(内存、IPC) | 极小(用户态) |
| 共享数据 | 直接共享(需加锁) | 需 Queue/Pipe/Manager | 直接共享(无需锁,单线程) |
| 适合场景 | I/O-bound、轻量并发 | CPU-bound | 大量 I/O-bound |
| 代码复杂度 | 低-中 | 中 | 中(需全链路 async) |
| 崩溃影响 | 可能拖垮整个进程 | 独立,互不影响 | 未处理异常会取消其他 task |
一句话选型:
- 爬虫 / API 请求 / 高并发网络:asyncio(首选),吞吐最高
- 传统 I/O 任务、兼容旧代码:threading
- 计算密集、要榨干 CPU:multiprocessing
- 混合场景:asyncio + run_in_executor(见进阶篇第 10 章)
进阶篇:同步原语与高级 API
入门篇讲的是"怎么跑起来",进阶篇讲的是"怎么正确地跑起来"。
5. threading 同步原语
多线程共享内存带来的竞争条件,需要用 synchronization primitive(同步原语) 来保护。
5.1 Lock / RLock:互斥锁
import threading
counter = 0
lock = threading.Lock() # 互斥锁,一次只允许一个线程持有
def safe_increment() -> None:
global counter
for _ in range(100_000):
with lock: # 等价于 lock.acquire() ... lock.release()
counter += 1
threads = [threading.Thread(target=safe_increment) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(f"结果: {counter}") # 稳定等于 400000
with lock: 是推荐写法,自动处理异常时的释放,避免死锁。
Lock:普通互斥锁,不可重入。同一线程两次acquire会死锁。RLock(可重入锁):同一线程可以多次acquire,但要对应次数release。适合递归或跨函数调用。
5.2 Semaphore / BoundedSemaphore:信号量
控制同时访问的线程数量上限——典型场景是"限流"。
import threading
import time
sem = threading.Semaphore(3) # 最多 3 个线程同时进入
def access_resource(i: int) -> None:
with sem:
print(f"线程 {i} 获得许可,开始工作")
time.sleep(1)
print(f"线程 {i} 释放许可")
threads = [threading.Thread(target=access_resource, args=(i,)) for i in range(10)]
for t in threads: t.start()
for t in threads: t.join()
BoundedSemaphore 会在 release 次数超过初始值时抛异常,用于检测逻辑错误。
5.3 Event:事件标志
Event 是一个内部标志,用于线程间"通知/等待"。
import threading
import time
event = threading.Event()
def waiter() -> None:
print("等待事件触发...")
event.wait() # 阻塞,直到 flag 被 set
print("事件已触发,继续执行!")
def setter() -> None:
time.sleep(2)
event.set() # 设置 flag,唤醒所有 waiter
threading.Thread(target=waiter).start()
threading.Thread(target=setter).start()
常用方法:.set()、.clear()、.wait(timeout=None)、.is_set()。
5.4 Condition:条件变量
Condition = Lock + wait/notify,用于"某个条件满足时才继续"的场景(如生产者-消费者)。
import threading
condition = threading.Condition()
data_ready = False
def consumer() -> None:
global data_ready
with condition:
while not data_ready:
condition.wait() # 释放锁并等待 notify
print("消费者:数据已就绪,开始消费")
def producer() -> None:
global data_ready
with condition:
print("生产者:准备数据...")
data_ready = True
condition.notify() # 唤醒一个等待者
threading.Thread(target=consumer).start()
threading.Thread(target=producer).start()
用
while而非if检查条件,防止虚假唤醒(spurious wakeup)。
5.5 Barrier:屏障
让一组线程在某个点集合,都到达后才一起放行。
import threading
import time
barrier = threading.Barrier(3) # 3 个线程会合
def racer(name: str) -> None:
time.sleep(0.5)
print(f"{name} 到达起跑线")
barrier.wait() # 阻塞,直到 3 个都到
print(f"{name} 开跑!")
for name in ["A", "B", "C"]:
threading.Thread(target=racer, args=(name,)).start()
6. 队列与线程/进程间通信
不要用全局变量 + 锁来传递数据。队列(Queue)是线程/进程间通信(IPC)的首选工具——它内部已处理好锁,安全且解耦。
6.1 queue.Queue 在线程间通信
import threading
import queue
import time
q = queue.Queue(maxsize=10) # maxsize 限制队列大小,put 满时阻塞
def producer() -> None:
for i in range(5):
q.put(f"数据-{i}")
print(f"生产: 数据-{i}")
time.sleep(0.3)
q.put(None) # 毒丸(poison pill),通知消费者结束
def consumer() -> None:
while True:
item = q.get()
if item is None: # 收到结束信号
q.put(None) # 传给下一个消费者
break
print(f"消费: {item}")
q.task_done()
p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)
p.start(); c.start()
p.join(); c.join()
6.2 multiprocessing.Queue 在进程间通信
接口与 queue.Queue 几乎一致,但底层用管道(pipe)+ 序列化实现跨进程传递。
import multiprocessing as mp
import time
def worker(q: mp.Queue) -> None:
for i in range(3):
q.put(f"进程-{mp.current_process().name}-项-{i}")
q.put(None)
def collector(q: mp.Queue) -> None:
while True:
item = q.get()
if item is None: break
print(f"收到: {item}")
if __name__ == "__main__":
q = mp.Queue()
producers = [mp.Process(target=worker, args=(q,)) for _ in range(2)]
collector_p = mp.Process(target=collector, args=(q,))
for p in producers: p.start()
collector_p.start()
for p in producers: p.join()
q.put(None) # 唤醒 collector
collector_p.join()
⚠️
multiprocessing.Queue需要启动一个后台 feeder 线程来序列化数据,因此它要求可 pickle 的对象,且只能在if __name__ == "__main__"保护内使用。
7. concurrent.futures:优雅的线程池与进程池
手动管理 Thread/Process 繁琐且易错。concurrent.futures 提供了高级抽象——Executor(执行器)自动管理池化、调度和结果收集。
7.1 ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor, as_completed
import urllib.request
urls = [
"https://www.python.org",
"https://docs.python.org",
"https://pypi.org",
]
def fetch(url: str) -> tuple[str, int]:
with urllib.request.urlopen(url, timeout=10) as resp:
data = resp.read()
return url, len(data)
# max_workers 控制并发数
with ThreadPoolExecutor(max_workers=4) as executor:
# submit 提交任务,返回 Future
future_to_url = {executor.submit(fetch, url): url for url in urls}
for future in as_completed(future_to_url):
url = future_to_url[future]
try:
result_url, size = future.result() # 获取结果(会抛原异常)
print(f"{result_url}: {size} bytes")
except Exception as e:
print(f"{url} 失败: {e}")
核心概念:
Executor:执行器,submit(fn, *args)提交任务返回FutureFuture:代表"未来会有的结果",可查状态、取结果、加回调、取消as_completed(fs):迭代器,哪个 future 先完成就先返回(谁快先处理谁)executor.map(fn, iterable):类似内置map,但并行执行(保持顺序)
7.2 ProcessPoolExecutor
把 ThreadPoolExecutor 换成 ProcessPoolExecutor,其余代码几乎不用改——这就是高级 API 的价值。
from concurrent.futures import ProcessPoolExecutor
import math
def is_prime(n: int) -> tuple[int, bool]:
if n < 2: return n, False
for i in range(2, int(math.isqrt(n)) + 1):
if n % i == 0: return n, False
return n, True
numbers = [10000019, 10000079, 10000103, 10000121, 10000139]
if __name__ == "__main__":
with ProcessPoolExecutor() as executor: # 默认 max_workers = 核数
results = list(executor.map(is_prime, numbers)) # 保持顺序
for n, ok in results:
print(f"{n}: {'质数' if ok else '非质数'}")
🔑
executor.map返回顺序与输入顺序一致;as_completed返回顺序是完成顺序。按需求选用。
7.3 Future 的常用方法
future = executor.submit(some_func)
future.running() # 是否正在运行
future.done() # 是否已完成(成功/异常/取消)
future.result(timeout=5) # 阻塞取结果,可设超时
future.cancel() # 尝试取消(仅未开始时可取消)
future.add_done_callback(fn) # 完成时回调
8. asyncio 进阶:Task、gather、wait、超时与取消
8.1 asyncio.create_task vs asyncio.gather
import asyncio
async def work(i: int) -> str:
await asyncio.sleep(1)
return f"任务{i}完成"
async def main() -> None:
# 方式一:create_task 逐个创建
t1 = asyncio.create_task(work(1))
t2 = asyncio.create_task(work(2))
r1 = await t1
r2 = await t2
# 方式二:gather 批量并发(更常用)
results = await asyncio.gather(work(3), work(4), work(5))
print(results) # ['任务3完成', '任务4完成', '任务5完成']
asyncio.run(main())
gather 特点:
- 并发运行所有传入的 awaitable
- 返回结果列表,顺序与输入一致
- 任一任务抛异常,
gather会立即传播该异常(其他任务不会被取消,除非设return_exceptions=False配合)
8.2 asyncio.wait:更精细的控制
wait 返回两个集合:(done, pending),配合 FIRST_COMPLETED / ALL_COMPLETED / FIRST_EXCEPTION 等条件使用。
import asyncio
async def slow(n: int) -> str:
await asyncio.sleep(n)
return f"{n}秒完成"
async def main() -> None:
tasks = [asyncio.create_task(slow(i)) for i in [3, 1, 2]]
done, pending = await asyncio.wait(tasks, timeout=2)
print(f"已完成: {[t.result() for t in done]}")
print(f"未完成: {len(pending)} 个")
asyncio.run(main())
gather vs wait 怎么选?
- 想批量拿全部结果、保持顺序 →
gather - 想拿到一个就处理一个、设超时、精细控制 →
wait
8.3 超时控制:wait_for
import asyncio
async def slow_op() -> str:
await asyncio.sleep(10)
return "结果"
async def main() -> None:
try:
result = await asyncio.wait_for(slow_op(), timeout=3)
except asyncio.TimeoutError:
print("超时了!")
asyncio.run(main())
wait_for 超时会取消被等待的 task。
8.4 Task 取消
import asyncio
async def cancellable() -> None:
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("被取消了,执行清理...")
raise # 重要:必须重新抛出,否则取消不会生效
else:
print("正常完成")
async def main() -> None:
task = asyncio.create_task(cancellable())
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main: 确认 task 已取消")
asyncio.run(main())
⚠️ 捕获
CancelledError后必须raise重新抛出,否则 task 会被标记为"正常完成",取消意图失效。Python 3.8+ 中CancelledError是BaseException的子类。
9. asyncio 同步原语与队列
asyncio 也提供了一套异步版的同步原语(用法与 threading 版几乎一致,但内部是非阻塞的):
9.1 async Lock / Semaphore / Event
import asyncio
# 异步锁
lock = asyncio.Lock()
async def safe_op():
async with lock: # 注意是 async with
# 临界区
pass
# 异步信号量(限流神器)
semaphore = asyncio.Semaphore(5) # 最多 5 个并发
async def limited_fetch(url):
async with semaphore:
return await fetch(url)
# 异步事件
event = asyncio.Event()
async def waiter():
await event.wait()
print("事件触发")
async def setter():
await asyncio.sleep(1)
event.set()
9.2 asyncio.Queue:异步生产者-消费者
import asyncio
async def producer(q: asyncio.Queue, n: int) -> None:
for i in range(n):
await q.put(f"数据-{i}")
print(f"生产: 数据-{i}")
await q.put(None) # 结束信号
async def consumer(q: asyncio.Queue) -> None:
while True:
item = await q.get()
if item is None:
await q.put(None) # 传给下一个消费者
break
print(f"消费: {item}")
q.task_done()
async def main() -> None:
q = asyncio.Queue()
await asyncio.gather(
producer(q, 5),
consumer(q),
)
asyncio.run(main())
asyncio.Queue 是异步爬虫和流式处理的核心组件。
10. asyncio 与同步世界的桥接
现实代码不可能全都是 async。asyncio 提供了机制来与同步代码互操作。
10.1 run_in_executor:把同步阻塞调用丢进线程池
这是最常用的桥接方式——把阻塞的同步函数放到线程池执行,避免污染 event loop。
import asyncio
import time
def blocking_io() -> str:
time.sleep(2) # 阻塞调用
return "IO 完成"
async def main() -> None:
loop = asyncio.get_running_loop()
# 把阻塞函数丢进默认线程池执行
result = await loop.run_in_executor(None, blocking_io)
print(result)
asyncio.run(main())
也可以指定自定义的 ThreadPoolExecutor 或 ProcessPoolExecutor:
import concurrent.futures
async def main():
loop = asyncio.get_running_loop()
with concurrent.futures.ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, cpu_bound_func, arg)
10.2 run_coroutine_threadsafe:从其他线程调度协程
在非 asyncio 线程里想调用协程时用:
import asyncio
import threading
async def async_work() -> str:
await asyncio.sleep(1)
return "done"
def sync_thread(loop: asyncio.AbstractEventLoop) -> None:
# 把协程提交到指定 loop 执行
future = asyncio.run_coroutine_threadsafe(async_work(), loop)
print(future.result()) # 阻塞等待结果
async def main() -> None:
loop = asyncio.get_running_loop()
threading.Thread(target=sync_thread, args=(loop,)).start()
await asyncio.sleep(2)
asyncio.run(main())
10.3 to_thread(Python 3.9+)
更简洁的语法糖:
import asyncio
def blocking() -> str:
time.sleep(2)
return "ok"
async def main() -> None:
result = await asyncio.to_thread(blocking)
print(result)
高阶篇:原理与陷阱
这一章深入"为什么"和"怎么避免坑"。
11. asyncio 底层原理:coroutine 是状态机
11.1 从生成器到 coroutine
早期(Python 3.4)的 asyncio 基于 @asyncio.coroutine + yield from 生成器实现。Python 3.5 引入 async/await 语法糖,本质是原生协程(native coroutine)。
一个 coroutine 在内部是一个状态机,可以被挂起和恢复:
import asyncio
async def gen_coro() -> None:
print(" 点1")
await asyncio.sleep(0)
print(" 点2")
await asyncio.sleep(0)
print(" 点3")
async def main() -> None:
coro = gen_coro()
print(f"创建后状态: {coro.cr_running=}") # 未运行
task = asyncio.create_task(coro)
await task
asyncio.run(main())
11.2 await 到底做了什么?
await X 的工作流程:
- 对
X求值,得到 awaitable 对象(coroutine / Task / Future 等) - 交出当前 coroutine 的执行权给 event loop
- event loop 调度其他就绪的 coroutine
- 当
X完成,event loop 把结果(或异常)送回这个 coroutine,从其挂起点恢复执行
这就是为什么异步代码"看起来是同步的,跑起来是并发的"。
11.3 send / throw / close(原生协程的低层接口)
coroutine 对象有 send(value)、throw(exc)、close() 方法,这是它被当作"可恢复函数"的底层契约。日常代码不用直接调用,但理解它们有助于读懂源码。
12. event loop 与 uvloop
12.1 event loop 是什么?
event loop 是 asyncio 的调度核心——一个无限循环,不断:
- 检查是否有就绪的 I/O 事件
- 执行已到期的定时器(timeout)
- 恢复等待这些事件的 coroutine
你可以把它理解为一个单线程里的"操作系统调度器"。
12.2 获取和操作 loop
import asyncio
async def main() -> None:
loop = asyncio.get_running_loop() # 获取当前运行的 loop
print(f"loop: {loop}")
print(f"pid: {loop.__class__.__name__}")
# 在 loop 上调度一个同步回调(下次迭代执行)
loop.call_soon(lambda: print("call_soon 执行"))
# 延迟调度
loop.call_later(1, lambda: print("1秒后执行"))
asyncio.run(main())
12.3 uvloop:让 asyncio 飞起来
uvloop 是用 Cython 基于 libuv 实现的 event loop,性能可达默认 loop 的 2-4 倍。
import asyncio
import uvloop
# 方式一:全局替换(Python 3.11+ 推荐)
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# 方式二:局部使用
loop = uvloop.new_event_loop()
asyncio.set_event_loop(loop)
安装:
pip install uvloop。注意 uvloop 主要支持 Linux/macOS,Windows 支持较新版本才完善。
13. 取消、超时与异常传播
13.1 异常在 gather 中的传播
import asyncio
async def boom() -> None:
raise ValueError("出错了")
async def good() -> str:
await asyncio.sleep(1)
return "ok"
async def main() -> None:
# return_exceptions=True:异常作为结果返回,不抛出
results = await asyncio.gather(boom(), good(), return_exceptions=True)
print(results) # [ValueError('出错了'), 'ok']
asyncio.run(main())
13.2 屏蔽取消:shield
有时某个关键操作不希望被取消:
import asyncio
async def critical() -> None:
await asyncio.sleep(10)
print("关键操作完成")
async def main() -> None:
task = asyncio.create_task(asyncio.shield(critical()))
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("task 被取消,但 critical 仍在后台运行")
asyncio.run(main())
13.3 超时上下文:timeout
Python 3.11+ 提供更优雅的超时写法:
import asyncio
async def main() -> None:
async with asyncio.timeout(3): # 3 秒超时
await asyncio.sleep(10)
# 超时后抛出 TimeoutError,并取消内部所有 task
asyncio.run(main())
14. 多进程共享状态与 IPC
由于进程间不共享内存,传递数据必须靠序列化 + IPC。
14.1 Queue / Pipe
已在第 6.2 节介绍 Queue。Pipe 是更底层的双工通道:
import multiprocessing as mp
if __name__ == "__main__":
parent_conn, child_conn = mp.Pipe()
parent_conn.send("hello from parent")
print(child_conn.recv()) # 阻塞接收
14.2 shared_memory(Python 3.8+)
真正的共享内存,零拷贝,性能最高:
import multiprocessing as mp
import numpy as np
def worker(shm_name: str) -> None:
from multiprocessing import shared_memory
shm = shared_memory.SharedMemory(name=shm_name)
arr = np.ndarray((5,), dtype=np.int64, buffer=shm.buf)
arr[0] = 999 # 直接修改共享内存
shm.close()
if __name__ == "__main__":
shm = mp.shared_memory.SharedMemory(create=True, size=40) # 5*8 bytes
arr = np.ndarray((5,), dtype=np.int64, buffer=shm.buf)
arr[:] = [1, 2, 3, 4, 5]
p = mp.Process(target=worker, args=(shm.name,))
p.start(); p.join()
print(arr) # [999, 2, 3, 4, 5] —— 被子进程修改了!
shm.close(); shm.unlink()
14.3 Manager:共享 Python 对象
Manager 提供进程间共享的 dict / list / Namespace / Value / Array 等,内部由代理进程实现,易用但性能较低(跨进程 RPC)。
import multiprocessing as mp
def update(shared_dict):
shared_dict["count"] += 1
if __name__ == "__main__":
with mp.Manager() as manager:
d = manager.dict({"count": 0})
procs = [mp.Process(target=update, args=(d,)) for _ in range(10)]
for p in procs: p.start()
for p in procs: p.join()
print(d["count"]) # 10
14.4 Value / Array
multiprocessing.Value 和 Array 通过共享内存提供简单类型的共享,配合 Lock 保证安全:
import multiprocessing as mp
def increment(counter):
with counter.get_lock():
counter.value += 1
if __name__ == "__main__":
counter = mp.Value("i", 0) # 'i' 表示 signed int
procs = [mp.Process(target=increment, args=(counter,)) for _ in range(100)]
for p in procs: p.start()
for p in procs: p.join()
print(counter.value)
15. 并发模式:生产者-消费者、扇出扇入
15.1 生产者-消费者模式(Queue + 多 Worker)
最经典、最实用的并发模式:
import asyncio
import random
async def producer(q: asyncio.Queue, n: int) -> None:
for i in range(n):
await asyncio.sleep(random.uniform(0.1, 0.5))
await q.put(i)
print(f"[生产] {i}")
await q.put(None) # 结束信号
async def consumer(q: asyncio.Queue, cid: int) -> None:
while True:
item = await q.get()
if item is None:
await q.put(None) # 传给其他消费者
break
await asyncio.sleep(random.uniform(0.2, 0.8))
print(f"[消费-{cid}] {item}")
q.task_done()
async def main() -> None:
q = asyncio.Queue(maxsize=5)
await asyncio.gather(
producer(q, 10),
*(consumer(q, i) for i in range(3))
)
asyncio.run(main())
15.2 扇出-扇入(Fan-out / Fan-in)
- Fan-out:一个任务拆成 N 个子任务并发执行
- Fan-in:把 N 个结果汇聚成一份
import asyncio
async def fetch_part(url: str) -> str:
await asyncio.sleep(1)
return f"来自 {url} 的数据"
async def fan_out(urls: list[str]) -> list[str]:
# Fan-out:并发发出所有请求
tasks = [asyncio.create_task(fetch_part(u)) for u in urls]
# Fan-in:汇聚结果
results = await asyncio.gather(*tasks)
return results
async def main() -> None:
urls = ["api/users", "api/posts", "api/comments"]
data = await fan_out(urls)
print(data)
asyncio.run(main())
这是数据聚合、并行爬虫、微服务编排的核心模式。
16. 常见陷阱与坑
16.1 阻塞调用污染 event loop
最致命的坑:在 async 函数中调用了阻塞的同步代码(如 time.sleep、requests.get),整个 event loop 会被卡住,所有协程一起停摆。
import asyncio
import time
async def bad() -> None:
time.sleep(3) # 灾难!整个 loop 被阻塞 3 秒
async def good() -> None:
await asyncio.sleep(3) # 正确:让出执行权
排查方法:开启 asyncio debug 模式,会自动检测长时间运行的回调:
import asyncio
asyncio.run(main(), debug=True)
16.2 忘记 await
async def fetch() -> str:
return "data"
async def main() -> None:
result = fetch() # 忘记 await!返回的是 coroutine 对象
print(result) # <coroutine object ...>
16.3 死锁:在锁里 await
lock = asyncio.Lock()
async def deadlock() -> None:
async with lock:
await deadlock() # 递归获取同一把 async lock → 死锁!
asyncio 的 Lock 是不可重入的,用 asyncio.Lock() 递归会死锁。需要重入时用自己封装或避免嵌套。
16.4 多线程下的可变全局状态
没有加锁地读写全局可变对象,会引发难以复现的数据错乱。
16.5 multiprocessing 在交互式环境(REPL/Jupyter)中报错
spawn 方式要求代码可被 import。在 Jupyter 中应使用 multiprocessing.get_context("fork") 或改用线程池,或用 %%time 魔法配合。
16.6 捕获 CancelledError 后不重新抛出
见第 8.4 节,务必 raise。
16.7 把不可 pickle 的对象传给进程池
进程间传参需要 pickle 序列化。lambda、闭包捕获的局部变量、文件句柄等往往无法 pickle,会抛 PicklingError。
17. GIL 演进与新版 Python 的影响
17.1 传统 GIL 行为回顾
CPython 靠 GIL 保护内存管理,代价是多线程无法并行 CPU 任务。多线程的优势仅在 I/O 等待释放 GIL 时体现。
17.2 Python 3.12 / 3.13 的改进
- Python 3.12:引入改进的 GIL 实现,减少了一些争用开销(PEP 684 相关工作铺垫)。
- Python 3.13:正式引入 "free-threaded" 构建(PEP 703)——可通过特殊编译版本完全移除 GIL,让多线程真正实现并行。
启用方式(3.13+):
./configure --disable-gil
python3.13t # 带 't' 后缀表示 free-threaded build
📌 现状:free-threaded 仍是实验性特性,第三方 C 扩展需要适配,性能在单线程场景可能略降。生产环境主流仍是带 GIL 版本,因此本文的"多进程处理 CPU-bound"建议依然适用。
17.3 对并发选型的影响
- I/O-bound:asyncio 仍是首选(free-threaded 不改变这一结论)
- CPU-bound:未来若 free-threaded 成熟,纯 Python 计算可考虑多线程;但涉及 NumPy 等释放 GIL 的 C 扩展,多线程已经能并行(这是个隐藏知识点)
- 兼容性:写库代码时仍应假设目标环境有 GIL
实战篇:项目级应用
理论讲完,进入四个完整实战案例。
实战 1:高并发异步爬虫
目标:并发抓取多个 URL,带限流、重试、超时、异常处理。用标准库 + aiohttp。
import asyncio
import aiohttp
from typing import Optional
# pip install aiohttp
class AsyncCrawler:
def __init__(self, concurrency: int = 10, timeout: float = 10.0):
self.semaphore = asyncio.Semaphore(concurrency) # 限流
self.timeout = aiohttp.ClientTimeout(total=timeout)
self.stats = {"success": 0, "failed": 0}
async def fetch(self, session: aiohttp.ClientSession, url: str,
retries: int = 3) -> Optional[str]:
async with self.semaphore: # 控制并发数
for attempt in range(retries):
try:
async with session.get(url, timeout=self.timeout) as resp:
resp.raise_for_status()
text = await resp.text()
self.stats["success"] += 1
return text
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if attempt == retries - 1:
self.stats["failed"] += 1
print(f"❌ {url} 最终失败: {e}")
return None
wait = 2 ** attempt # 指数退避
await asyncio.sleep(wait)
print(f"⚠️ {url} 第{attempt+1}次失败,{wait}s 后重试")
async def crawl(self, urls: list[str]) -> list[Optional[str]]:
# 使用 TCPConnector 限制连接池
connector = aiohttp.TCPConnector(limit=20)
async with aiohttp.ClientSession(
connector=connector, timeout=self.timeout
) as session:
# 扇出:并发抓取
tasks = [asyncio.create_task(self.fetch(session, url)) for url in urls]
# 扇入:汇聚结果
results = await asyncio.gather(*tasks, return_exceptions=False)
return results
async def main() -> None:
urls = [
"https://www.python.org",
"https://docs.python.org",
"https://pypi.org",
"https://github.com",
"https://stackoverflow.com",
] * 3 # 重复几次模拟更多请求
crawler = AsyncCrawler(concurrency=8, timeout=10)
results = await crawler.crawl(urls)
print(f"\n抓取完成: 成功 {crawler.stats['success']}, "
f"失败 {crawler.stats['failed']}, "
f"总大小 {sum(len(r) for r in results if r):,} bytes")
asyncio.run(main())
用到的知识点:
asyncio.Semaphore限流(第 9.1 节)gather扇出扇入(第 8.1 节、第 15.2 节)- 指数退避重试
- 连接池控制(
TCPConnector)
实战 2:CPU 密集型数据的进程池流水线
目标:用 ProcessPoolExecutor 并行处理大量 CPU 密集型计算。
import concurrent.futures as cf
import math
import time
def is_prime(n: int) -> tuple[int, bool]:
"""判断质数(CPU 密集型)。"""
if n < 2: return n, False
if n % 2 == 0: return n, n == 2
for i in range(3, int(math.isqrt(n)) + 1, 2):
if n % i == 0: return n, False
return n, True
def chunk_primes(args: tuple[range, int]) -> list[tuple[int, bool]]:
"""处理一个数据块。第二个参数是 worker id,便于日志。"""
chunk, worker_id = args
results = [is_prime(n) for n in chunk]
print(f" worker-{worker_id} 处理完 {len(results)} 个")
return results
def split_chunks(data: range, n_chunks: int) -> list[tuple[range, int]]:
total = len(data)
step = math.ceil(total / n_chunks)
return [
(range(data.start + i * step, min(data.start + (i + 1) * step, data.stop)), i)
for i in range(n_chunks)
]
def main() -> None:
numbers = range(2, 200_000)
n_workers = cf.ProcessPoolExecutor()._max_workers # 默认=CPU 核数
print(f"使用 {n_workers} 个进程")
chunks = split_chunks(numbers, n_workers * 2) # 2x 超量分块,负载均衡
t0 = time.time()
with cf.ProcessPoolExecutor() as executor:
# map 保持顺序;用 chunks 减少 IPC 次数(分块很重要!)
all_results = list(executor.map(chunk_primes, chunks))
elapsed = time.time() - t0
flat = [item for chunk in all_results for item in chunk]
primes = [n for n, ok in flat if ok]
print(f"耗时: {elapsed:.2f}s, 找到 {len(primes)} 个质数")
if __name__ == "__main__":
main()
用到的知识点:
ProcessPoolExecutor(第 7.2 节)- 分块(chunking):把大量小任务合并成块,减少进程间 IPC 次数——这是性能关键
- 2x 超量分块实现负载均衡(避免"一核有难,多核围观")
实战 3:I/O + CPU 混合模型
目标:从网络下载数据(I/O)→ 解析计算(CPU)→ 保存。演示 asyncio + 进程池协作。
import asyncio
import aiohttp
import concurrent.futures as cf
from multiprocessing import cpu_count
# 下载是 I/O,解析是 CPU,两者用不同模型
async def download(session: aiohttp.ClientSession, url: str) -> str:
async with session.get(url) as resp:
return await resp.text()
def parse(html: str) -> dict:
"""CPU 密集型解析。"""
return {"len": len(html), "a_count": html.count("<a")}
async def process_url(url: str, session: aiohttp.ClientSession,
process_pool: cf.ProcessPoolExecutor) -> dict:
# I/O 阶段:asyncio 并发下载
html = await download(session, url)
# CPU 阶段:丢进进程池,不阻塞 event loop
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(process_pool, parse, html)
return {"url": url, **result}
async def main() -> None:
urls = ["https://www.python.org", "https://docs.python.org", "https://pypi.org"]
with cf.ProcessPoolExecutor(max_workers=cpu_count()) as pool:
async with aiohttp.ClientSession() as session:
tasks = [process_url(u, session, pool) for u in urls]
results = await asyncio.gather(*tasks)
for r in results:
print(r)
asyncio.run(main())
核心思想:用 asyncio 处理 I/O,用 ProcessPoolExecutor 处理 CPU,通过 run_in_executor 桥接(第 10.1 节)。这是生产环境中最优雅的混合方案。
实战 4:异步任务调度器雏形
目标:实现一个简单的周期性任务调度器(类似轻量版 Celery)。
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable
@dataclass
class Job:
name: str
coro_func: Callable[[], Awaitable]
interval: float
max_runs: int = 0 # 0 = 无限
class Scheduler:
def __init__(self):
self.jobs: list[Job] = []
self._tasks: list[asyncio.Task] = []
def add_job(self, job: Job) -> None:
self.jobs.append(job)
async def _run_job(self, job: Job) -> None:
runs = 0
while True:
if job.max_runs and runs >= job.max_runs:
break
try:
await job.coro_func()
runs += 1
except Exception as e:
print(f"❌ 任务 {job.name} 出错: {e}")
await asyncio.sleep(job.interval)
async def run(self) -> None:
self._tasks = [
asyncio.create_task(self._run_job(job)) for job in self.jobs
]
# 等待所有任务(一般跑很久)
await asyncio.gather(*self._tasks)
def stop(self) -> None:
for task in self._tasks:
task.cancel()
# ===== 使用 =====
async def heartbeat() -> None:
print(f"💓 心跳: {asyncio.get_event_loop().time():.0f}s")
async def cleanup() -> None:
print("🧹 清理任务执行")
async def main() -> None:
scheduler = Scheduler()
scheduler.add_job(Job("heartbeat", heartbeat, interval=2, max_runs=3))
scheduler.add_job(Job("cleanup", cleanup, interval=5, max_runs=1))
try:
await scheduler.run()
except KeyboardInterrupt:
scheduler.stop()
asyncio.run(main())
用到的知识点:
create_task+gather管理多个长期运行任务(第 8.1 节)- 取消机制(第 8.4 节)
- 异常隔离:单任务异常不影响调度器
调试、性能剖析与测试
调试
import asyncio
# 开启 asyncio debug 模式:检测未等待的协程、慢回调
asyncio.run(main(), debug=True)
# 或全局开启
asyncio.get_event_loop().set_debug(True)
开启后会打印:
- 未
await的协程警告 - 执行超过 100ms 的回调(可配置阈值)
- 未关闭的资源警告
性能剖析
cProfile:标准库,统计函数耗时py-spy:采样剖析器,可无侵入地剖析运行中的 Python 进程,对生产环境友好pip install py-spy py-spy top --pid 12345 # 实时查看 py-spy dump --pid 12345 # 导出当前调用栈 py-spy record -o flame.svg --pid 12345 # 生成火焰图
测试异步代码
用 pytest + pytest-asyncio:
import pytest
import asyncio
@pytest.mark.asyncio
async def test_fetch():
async def dummy():
await asyncio.sleep(0.1)
return 42
result = await dummy()
assert result == 42
最佳实践清单
最后,把全文浓缩成一份可执行的检查清单:
asyncio
threading
multiprocessing
通用
延伸阅读与第三方库速览
| 库 | 定位 | 说明 |
|---|---|---|
| aiohttp | 异步 HTTP 客户端/服务端 | asyncio 生态事实标准 |
| httpx | 支持 HTTP/2、异步的 HTTP 客户端 | 兼容 requests API,更现代 |
| uvloop | 高性能 event loop | 基于 libuv,2-4 倍加速 |
| anyio | 异步后端兼容层 | 抽象 asyncio/trio 差异 |
| trio | 结构化并发异步库 | 强调"结构化并发",API 更现代 |
| celery | 分布式任务队列 | 生产级异步任务调度 |
| dask | 并行计算 | 大数据并行处理 |
结语
Python 的并发编程看似三大套东西(线程、进程、协程),其实有一条清晰的脉络:
并发问题的本质 → 是 I/O 等待还是 CPU 计算?
├── I/O-bound ──→ asyncio(首选)/ threading
└── CPU-bound ──→ multiprocessing
混合场景 ─────────→ asyncio + run_in_executor(ProcessPoolExecutor)
掌握这条主线,再理解每个模型的同步原语、坑点和调试手段,就能从容应对绝大多数并发场景。祝编码愉快!🚀
浙公网安备 33010602011771号