第 06 章:并发模型与多任务架构
第 06 章:并发模型与多任务架构
并发处理是构建高性能、高吞吐系统的核心能力。由于 CPython 历史上的 GIL 锁限制,Python 形成了独特的并发三剑客体系:多线程 (Threading) 、多进程 (Multiprocessing) 与 协程异步 I/O (Asyncio)。
6.1 GIL (Global Interpreter Lock 全局解释器锁) 深度剖析
1. 为什么存在 GIL?
在 CPython 中,内存管理基于引用计数 (ob_refcnt)。如果没有锁机制保护,多线程同时修改同一个对象的引用计数会导致严重的竞态条件 (Race Condition) 与内存损坏。
为了保证 CPython 内存分配与 C 扩展模块的线程安全,Guido 在 CPython 诞生初期引入了全局解释器锁(GIL)。
核心定义:GIL 是 CPython 解释器级别的一个全局互斥锁,保证在任何给定的时刻,只有一个 OS 线程能在 CPython 虚拟机中执行 Python 字节码。
CPU Core 1 CPU Core 2
┌───────────────────┐ ┌───────────────────┐
Thread 1 │ 获得 GIL, 执行 │ │ 阻塞等待 GIL... │ (即使硬件存在 8 核 CPU,
└───────────────────┘ └───────────────────┘ 纯 Python 字节码也只能
│ (时钟中断/I/O) 利用单核 CPU !)
▼
Thread 2 │ 阻塞等待 GIL... │ │ 获得 GIL, 执行 │
└───────────────────┘ └───────────────────┘2. GIL 的工作机制与 I/O 释放
GIL 并不是一锁到底不释放的:
- I/O 操作自动释放:当线程发起文件读写、Socket 网络请求或
time.sleep()等阻塞 I/O 时,CPython 会主动释放 GIL,允许其他线程获取 GIL 并执行。因此,多线程对于 I/O 密集型任务依然是有效的。 - 时间片/指令轮转释放:Python 3 引入了基于时间间隔(默认 5ms)的 GIL 抢占机制。CPU 密集型线程执行满 5ms 后必须强制释放 GIL 并重新竞争。
3. Python 3.13 无 GIL 自由线程 (Free-threaded) 演进
PEP 703 提案正式在 Python 3.13 中引入了可选的无 GIL 编译构建(--disable-gil):
- 采用细粒度的锁机制(如 Mimalloc 动态内存分配器与 Biased Reference Counting 偏向引用计数)。
- 在无 GIL 构建下,纯 Python 多线程能够在多核 CPU 上实现线性的 CPU 算力并行翻倍!
6.2 多线程编程 (threading & ThreadPoolExecutor)
多线程适合处理 I/O 密集型任务(如并发抓取网页、文件下载、数据库查询聚合)。
使用 ThreadPoolExecutor 线程池高并发抓取
from concurrent.futures import ThreadPoolExecutor, as_completed
import urllib.request
import time
URLS = [
"https://www.python.org",
"https://pypi.org",
"https://docs.python.org",
]
def fetch_url(url: str) -> tuple[str, int]:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=5) as response:
html = response.read()
return url, len(html)
start_time = time.perf_counter()
# 启动包含 5 个工作线程的线程池
with ThreadPoolExecutor(max_workers=5) as executor:
# 提交任务映射
future_to_url = {executor.submit(fetch_url, url): url for url in URLS}
for future in as_completed(future_to_url):
url = future_to_url[future]
try:
url_res, size = future.result()
print(f"✅ {url_res} 下载完成,大小: {size} bytes")
except Exception as exc:
print(f"❌ {url} 发生异常: {exc}")
print(f"⏱️ 多线程并发总耗时: {time.perf_counter() - start_time:.2f}s")6.3 多进程编程 (multiprocessing & ProcessPoolExecutor)
多进程通过衍生独立的 CPython 进程实例(拥有各自独立的 GIL 和内存空间),实现真正的 CPU 密集型物理多核并行(如图像处理、矩阵计算、大文件哈希计算)。
使用 ProcessPoolExecutor 计算 CPU 密集型任务
from concurrent.futures import ProcessPoolExecutor
import time
def cpu_heavy_task(n: int) -> int:
"""CPU 密集型计算:求平方和"""
return sum(i * i for i in range(n))
if __name__ == "__main__":
tasks = [10_000_000, 10_000_000, 10_000_000, 10_000_000]
start = time.perf_counter()
# 借助多进程避开 GIL,开启 4 个独立 Python 进程并行计算
with ProcessPoolExecutor(max_workers=4) as executor:
results = list(executor.map(cpu_heavy_task, tasks))
print(f"✅ 多进程并行结果: {results}")
print(f"⏱️ 4核多进程总耗时: {time.perf_counter() - start:.2f}s")注意:多进程在 Windows / macOS 上采用
spawn方式启动,因此创建进程的开销比线程高;且进程间内存不共享,跨进程通信(IPC)需要通过Queue或序列化pickle传输。
6.4 协程与异步 I/O (asyncio)
asyncio 采用与 Node.js 类似的单线程事件循环 (Event Loop) 机制。协程(Coroutine)是轻量级的用户态线程,当遇到 await 异步 I/O 操作时,自动将 CPU 控制权交还给事件循环,调度其他协程执行。
asyncio 高并发请求与任务组 (TaskGroup, Python 3.11+)
import asyncio
import time
async def async_fetch_api(service_id: int, delay: float) -> str:
print(f"📡 发起 API 异步请求 Service-{service_id}...")
# 模拟非阻塞网络 I/O,让出 CPU 给事件循环
await asyncio.sleep(delay)
print(f"✅ Service-{service_id} 响应返回!")
return f"Result-{service_id}"
async def main():
start = time.perf_counter()
# Python 3.11+ 推荐的 TaskGroup 上下文管理器 (具备严格的异常传播与资源清理)
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(async_fetch_api(1, 2.0))
task2 = tg.create_task(async_fetch_api(2, 1.0))
task3 = tg.create_task(async_fetch_api(3, 1.5))
# 所有任务执行完成后继续
print(f"所有结果: {[task1.result(), task2.result(), task3.result()]}")
print(f"⏱️ 协程异步并发总耗时: {time.perf_counter() - start:.2f}s (仅等于最长耗时 2.0s!)")
if __name__ == "__main__":
asyncio.run(main())6.5 三者对比与并发选型决策矩阵
并发任务选型决策树
│
任务类型是什么?
│
┌───────────────────────┴───────────────────────┐
▼ ▼
CPU 密集型任务 I/O 密集型任务
(矩阵计算/算法/加密/图片) (网络API请求/数据库/文件读写)
│ │
使用【多进程 Multiprocessing】 连接数与并发规模如何?
(或使用 PyO3/Rust 扩展) │
┌───────────────┴───────────────┐
▼ ▼
中度并发 (几十个) 超高并发 (数万长连接/SSE/WebSocket)
│ │
使用【多线程 Threading】 使用【协程 Asyncio】| 维度 | 多线程 (Threading) | 多进程 (Multiprocessing) | 协程 (Asyncio) |
|---|---|---|---|
| 工作实体 | 操作系统内核线程 | 独立 OS 进程 | 单线程内的协程函数 (用户态) |
| 内存开销 | 中等 (几 MB / 线程) | 较高 (数十 MB / 进程) | 极低 (几 KB / 协程) |
| GIL 影响 | 受限制 (无法利用物理多核) | 完全不受限制 (避开 GIL) | 不受影响 (单线程事件循环) |
| 适用场景 | 传统 I/O 密集型、阻塞式 API | CPU 密集型计算、图像视频处理 | 高并发网络 API、微服务、实时推送 |
| 数据共享 | 共享进程内存 (需 Lock 防竞争) | 内存隔离 (需 IPC 消息传递/Pickle) | 共享进程内存 (无需加锁) |
