====== 第三十一章:并发模式与最佳实践 ====== ===== 本章目标 ===== 完成本章学习后,你将能够: * 选择合适的并发模型 * 避免常见并发陷阱 * 优化并发性能 ===== 并发模型选择 ===== | 场景 | 推荐方案 | | I/O密集型,大量连接 | asyncio | | I/O密集型,少量任务 | 多线程 | | CPU密集型 | 多进程 | | 简单并行 | concurrent.futures | ===== 生产者消费者模式 ===== import asyncio import random async def producer(queue, n): for i in range(n): item = f"item_{i}" await queue.put(item) print(f"Produced {item}") await asyncio.sleep(random.random()) await queue.put(None) # 结束信号 async def consumer(queue): while True: item = await queue.get() if item is None: break print(f"Consumed {item}") await asyncio.sleep(random.random()) async def main(): queue = asyncio.Queue(maxsize=10) await asyncio.gather( producer(queue, 20), consumer(queue) ) asyncio.run(main()) ===== 本章练习 ===== 1. 实现线程池/进程池/协程池对比 2. 实现高性能下载器 3. 实现并发限制器 下一章:[[python_course:chapter32|第三十二章:SQLite数据库]]