Python 多线程与多进程实战:性能提升与陷阱揭秘
在处理 CPU 密集型或 IO 密集型任务时,Python 的并发编程能力显得尤为关键。
本篇文章将深入浅出地介绍 Python 中的多线程、多进程与协程的区别、使用场景,并通过真实案例演示它们的优势与潜在陷阱。
一、线程 vs 进程:到底该选谁?
| 特性 | 多线程 threading |
多进程 multiprocessing |
|---|---|---|
| 执行单位 | 线程(共享内存) | 独立进程(独立内存) |
| 开销 | 小 | 大 |
| 适合场景 | IO 密集任务 | CPU 密集任务 |
| 全局锁 GIL | 是 | 否 |
✅ 简单判断:网络请求/文件下载 用多线程,大规模计算/图像处理 用多进程
二、多线程实战:批量请求网页
python
复制编辑
import threading import requests import time urls = ["https://httpbin.org/delay/2"] * 5 def fetch(url): print(f"开始请求:{url}") response = requests.get(url) print(f"完成:{url}, 状态码: {response.status_code}") start = time.time() threads = [] for url in urls: t = threading.Thread(target=fetch, args=(url,)) t.start() threads.append(t) for t in threads: t.join() print("耗时:", time.time() - start)
⏱️ 效果对比(串行 vs 并发):
-
串行执行时间 ≈ 10 秒
-
多线程执行时间 ≈ 2~3 秒
三、多进程实战:并行计算
python
复制编辑
from multiprocessing import Process import time def compute(): print(f"开始计算...") sum([i**2 for i in range(10_000_000)]) print(f"完成计算") if __name__ == "__main__": start = time.time() p1 = Process(target=compute) p2 = Process(target=compute) p1.start() p2.start() p1.join() p2.join() print("总耗时:", time.time() - start)
✅ 优势:
-
多核并行(CPU 任务更快)
-
避免 GIL 限制
四:线程池与进程池(并发优化利器)
使用线程池
python
复制编辑
from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=5) as executor: executor.map(fetch, urls)
使用进程池
python
复制编辑
from concurrent.futures import ProcessPoolExecutor with ProcessPoolExecutor() as executor: executor.map(compute, range(2))
五、常见陷阱与注意事项
| 问题类型 | 说明 |
|---|---|
| GIL 限制 | Python 默认 GIL 阻止了真正的多线程 |
| 进程间通信复杂 | 多进程需使用 Queue/Pipe 等通信机制 |
| 资源冲突 | 多线程下注意共享资源加锁 |
| debug 困难 | 多线程/进程下出错信息不好追踪 |
六、进阶推荐:协程 async(IO 优化神器)
如果你追求极致 IO 性能,可以考虑 asyncio 协程:
python
复制编辑
import asyncio import aiohttp async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: print(await resp.text()) async def main(): urls = ["https://httpbin.org/get"] * 5 tasks = [fetch(url) for url in urls] await asyncio.gather(*tasks) asyncio.run(main())
✅ 协程适用于:大量并发、轻量级、事件驱动 场景,例如爬虫、消息系统
七、总结与建议
| 场景 | 推荐方式 |
|---|---|
| 多个网页请求 | 多线程 / 协程 |
| 文件 IO / 下载 | 多线程 |
| 数值计算 | 多进程 |
| 超大并发 | 协程(asyncio) |
| 简化写法 | 使用 Executor |
https://bigu.wang
https://www.bigu.wang
https://binm.wang
https://www.binm.wang
https://bint.wang
https://www.bint.wang
https://biop.wang
https://www.biop.wang
https://bits.wang
https://www.bits.wang
https://bjqb.wang
https://www.bjqb.wang
https://bjsm.wang
https://www.bjsm.wang
https://bleo.wang
https://www.bleo.wang
https://ono.wang
https://www.ono.wang
https://onz.wang
https://www.onz.wang
https://opo.wang
https://www.opo.wang
https://osm.wang
https://www.osm.wang
https://osn.wang
https://www.osn.wang
https://ovi.wang
https://www.ovi.wang
https://oxq.wang
https://www.oxq.wang
https://oti.wang
https://www.oti.wang
https://owu.wang
https://www.owu.wang
https://piq.wang
https://www.piq.wang
https://qmi.wang
https://www.qmi.wang
https://qki.wang
https://www.qki.wang
https://ref.wang
https://www.ref.wang
https://sak.wang
https://www.sak.wang
https://sar.wang
https://www.sar.wang
https://sfa.wang
https://www.sfa.wang
https://sfe.wang
https://www.sfe.wang
https://sgo.wang
https://www.sgo.wang
https://sku.wang
https://www.sku.wang
https://ycxjz.cn
https://www.ycxjz.cn
https://bnbmhomes.cn
https://www.bnbmhomes.cn
https://jinjianzuche.com
https://www.jinjianzuche.com
https://ahswt.cn
https://www.ahswt.cn
https://szwandaj.cn
https://www.szwandaj.cn
https://psbest.cn
https://www.psbest.cn
https://shanghai-arnold.cn
https://www.shanghai-arnold.cn
https://zgsscw.com
https://www.zgsscw.com
https://shxqth.cn
https://www.shxqth.cn
https://wdxj.cn
https://www.wdxj.cn
https://jad168.com
https://www.jad168.com
https://ultratrailms.cn
https://www.ultratrailms.cn
https://tztsjd.cn
https://www.tztsjd.cn
https://csqcbx.cn
https://www.csqcbx.cn
https://qazit.cn
https://www.qazit.cn
https://ahzjyl.cn
https://www.ahzjyl.cn
更多推荐


所有评论(0)