并发编程是提升程序性能的关键技术。本文介绍 Python 中最常用的 5 种并发模式。
1. Threading 模式
适用于 I/O 密集型 任务,如网络请求、文件读写。
python
import threading
import requests
def fetch_url(url):
response = requests.get(url)
print(f"{url}: {len(response.content)} bytes")
urls = ["http://example.com"] * 5
threads = []
for url in urls:
t = threading.Thread(target=fetch_url, args=(url,))
t.start()
threads.append(t)
for t in threads:
t.join()2. Multiprocessing 模式
适用于 CPU 密集型 任务,绕过 GIL 限制。
3. Asyncio 模式
适用于高并发 I/O 场景,如 Web 爬虫、API 网关。
4. ThreadPoolExecutor
更高级的线程池管理。
5. ProcessPoolExecutor
更高级的进程池管理。
选择建议
| 场景 | 推荐模式 |
|---|---|
| 爬虫/网络请求 | Asyncio |
| 数据处理/计算 | Multiprocessing |
| 简单并发 | Threading |
| 生产环境 | Executor 池 |
评论
0评论加载中…