python:chapter31

第三十一章:并发模式与最佳实践

完成本章学习后,你将能够:

  • 选择合适的并发模型
  • 避免常见并发陷阱
  • 优化并发性能
场景 推荐方案
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. 实现并发限制器

下一章:第三十二章:SQLite数据库

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • python/chapter31.txt
  • 最后更改: 2026/04/09 14:39
  • 张叶安