Ubuntu 上的 Python 并发编程模型与选型
一 概览与选型
二 快速上手示例
多线程
import threading
def worker(i):
print(f"Thread-{i} running")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for t in threads: t.start()
for t in threads: t.join()
多进程
import multiprocessing as mp
def worker(i):
print(f"Process-{i} running")
procs = [mp.Process(target=worker, args=(i,)) for i in range(3)]
for p in procs: p.start()
for p in procs: p.join()
异步 asyncio
import asyncio
async def worker(i):
print(f"Worker-{i} start")
await asyncio.sleep(1)
print(f"Worker-{i} done")
async def main():
await asyncio.gather(*(worker(i) for i in range(3)))
asyncio.run(main())
协程库 gevent
import gevent
from gevent import monkey; monkey.patch_all()
def worker(i):
print(f"Greenlet-{i} running")
gevent.sleep(1)
print(f"Greenlet-{i} done")
jobs = [gevent.spawn(worker, i) for i in range(3)]
gevent.joinall(jobs)
线程/进程池 concurrent.futures
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def task(x):
return x * x
# 线程池
with ThreadPoolExecutor(max_workers=4) as ex:
print(ex.map(task, range(5)))
# 进程池
with ProcessPoolExecutor(max_workers=4) as ex:
print(ex.map(task, range(5)))
以上示例均为 Ubuntu 可直接运行的 Python 3 代码范式。
三 模型对比与适用场景
| 模型 | 并发单元 | 并行度与 GIL | 典型场景 | 主要优点 | 主要注意点 |
|---|---|---|---|---|---|
| threading | 线程 | 受 GIL 影响,CPU 密集难并行;I/O 并发有效 | 高并发 I/O、轻量任务 | 共享内存、开销小 | 需同步原语;CPU 密集不占优 |
| multiprocessing | 进程 | 多进程可并行利用多核 | CPU 密集、大任务 | 真正并行、隔离性好 | 进程/通信开销大、内存占用高 |
| asyncio | 协程 | 单线程事件循环,非并行 | 大量 I/O、网络爬虫、微服务 | 高并发、低开销 | 全栈需异步;阻塞调用需适配 |
| gevent | greenlet | 协作式并发,非并行 | 高并发网络 I/O | 编程简单、生态成熟 | 需 monkey.patch_all();调试复杂度 |
| concurrent.futures | 线程/进程池 | 依后端而定 | 快速并行化既有函数 | 接口统一、易迁移 | 结果/超时/回调需合理设计 |
说明:GIL 使同一时刻仅有一个线程执行 Python 字节码,故多线程在 CPU 密集场景难以提速;而在 I/O 密集场景,线程在等待 I/O 时会释放 GIL,从而提升总体吞吐。
四 实践建议
五 在 Ubuntu 上的运行与安装要点
python3 --version 检查;如需安装:sudo apt update && sudo apt install python3 python3-pip。pip3 install gevent aiohttp 安装。python3 your_script.py;异步示例需 Python 3.7+ 使用 asyncio.run(),旧版本可用事件循环 API。