Python 并发与异步 MOC
线程、进程、GIL、Executor 与 asyncio 的阶段导航;先分清工作负载、调度层次与资源边界,再选择 native async、thread 或 process。
#moc
#growing
#dev
#python
#python
[!info] related notes
- 父 MOC: Python MOC
- 学习路线: Python 学习路线 MOC
Python 并发与异步 MOC
知识总览
filters:
and:
- 'file.ext == "md"'
- 'file.inFolder("z")'
- 'this.file.links.contains(file)'
- 'file.path != this.file.path'
formulas:
knowledge: 'file.asLink(title)'
properties:
formula.knowledge:
displayName: 知识
note.description:
displayName: Description
note.mastery:
displayName: Mastery
views:
- type: table
name: 知识总览
order:
- formula.knowledge
- note.description
- note.mastery
columnSize:
formula.knowledge: 280
note.description: 760
note.mastery: 56
从这里开始
推荐按“先分清模型 → 再理解执行资源 → 最后进入 asyncio 生命周期”的顺序:
一张选型地图
任务会明显耗时吗?
│
├─ 否 → 直接同步执行
│
└─ 是
│
├─ 大部分时间在等待 I/O?
│ ├─ 有 native async API → asyncio / await
│ └─ 只有 sync API → ThreadPool / asyncio.to_thread
│
└─ 大部分时间在计算?
├─ native library / 可能释放 GIL → bounded thread + benchmark
└─ heavy pure Python → ProcessPool / worker
同时记住三层调度:
Coroutine → Event Loop 协作式调度
Thread / Process → OS 抢占式调度
Python bytecode on traditional CPython Threads → 还受 GIL 约束
笔记列表
- 并发模型总览:先分清 concurrency、parallelism、I/O-bound、CPU-bound。
- GIL 与线程:理解 OS Thread 能多核调度,但传统 CPython bytecode 仍要争 GIL。
- Executor、Thread、Process 与 asyncio.to_thread:解释
to_thread到底做了什么,以及 native async、ThreadPool、ProcessPool 如何选。 - 多进程与进程池:纯 Python CPU 多核并行、pickle/IPC 与独立内存成本。
- 异步编程:Event Loop、coroutine、Task 与 I/O 并发。
- 任务、超时与取消:结构化并发、deadline 与 cancellation。
- 同步原语与队列:共享状态、Lock、Event、Queue 与 ownership。
真实项目应用
- BodySense Event Loop Blocking 边界:同步 psycopg 与 local model 如何阻塞 FastAPI Event Loop。
- BodySense Embedding 的 Async 执行边界:remote embedding、local transformer、hashing 为什么需要不同 execution model。
- BodySense KnowledgeLibrary 的 Async Postgres Pool:native async DB + connection pool + backpressure。