并发基础
这里只建立概念与最小示例,不展开生产级并发细节。
何时需要并发
- I/O 密集:等网络、等磁盘 —— 适合线程或 asyncio
- CPU 密集:大量计算 —— 常看多进程(本篇不展开)
threading 最小示例
import threading
import time
def worker(name: str):
time.sleep(0.1)
print(f"done {name}")
threads = [threading.Thread(target=worker, args=(f"t{i}",)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
注意:CPython 有 GIL,多线程不擅长抬高纯 CPU 吞吐;但适合并发等 I/O。
asyncio 最小示例
import asyncio
async def worker(name: str):
await asyncio.sleep(0.1)
print(f"done {name}")
async def main():
await asyncio.gather(worker("a"), worker("b"), worker("c"))
asyncio.run(main())
async def定义协程await等待可等待对象- 单线程协作式调度,适合高并发 I/O
怎么选(粗规则)
| 场景 | 常见选择 |
|---|---|
| 简单阻塞 I/O、脚本 | threading |
| 大量网络并发、现代异步库 | asyncio |
| 纯 CPU 重计算 | multiprocessing(另学) |
要点
- 先分清 I/O 密集 vs CPU 密集
- 线程与协程都能「同时等待」;模型不同
- 共享可变状态要加锁/队列,否则难查的竞态