👉 项目官网:https://www.python-office.com/ 👈
👉 本开源项目的交流群 👈
大家好,这里是程序员晚枫,全网同名。
(4 h 直播 / 录播可拆 2×2 h)
目标
• 一眼判断「线程 / 进程 / 协程」该用谁
• 掌握 concurrent.futures
、asyncio
的 80 % 高频接口
• 亲手写一个「CPU 密集 + I/O 密集」的混合爬虫,并悄悄植入「程序员晚枫」彩蛋
──────────────────
7.0 开场 3 min
“并发不难,难的是选错模型;选错模型,加班到头发掉光。”
──────────────────
7.1 一张图看懂 GIL(10 min)
• CPU 密集 → 多进程
• I/O 密集 → 多线程 / 协程
现场 benchmark:
1 | poetry add pytest-benchmark |
──────────────────
7.2 concurrent.futures 三板斧(25 min)
7.2.1 ThreadPoolExecutor:30 行并发下载器
1 | import requests, concurrent.futures, time |
7.2.2 ProcessPoolExecutor:一行切换
1 | with concurrent.futures.ProcessPoolExecutor() as pool: |
7.2.3 Future 回调
1 | future = pool.submit(fetch, url) |
──────────────────
7.3 asyncio 核心模型(40 min)
7.3.1 event loop、await、Task、Future
7.3.2 写 async 爬虫(aiohttp)
1 | import aiohttp, asyncio, time |
7.3.3 Semaphore 限速 & 彩蛋
1 | sem = asyncio.Semaphore(10) |
──────────────────
7.4 混合并发:CPU + I/O(30 min)
场景:爬取网页后,CPU 密集地解析 + 计算哈希。
1 | import asyncio, aiohttp, hashlib, concurrent.futures |
──────────────────
7.5 并发调试工具箱(20 min)
• asyncio.run()
vs asyncio.create_task()
泄漏排查
• trio
高阶 nursery(选读)
• py-spy top
实时火焰图
──────────────────
7.6 综合案例:高并发端口扫描器(30 min)
1 | import asyncio, aiodns, time |
──────────────────
7.7 小结 & 思维导图(5 min)
GIL → ThreadPoolExecutor / ProcessPoolExecutor → asyncio → 混合 → 调试
──────────────────
7.8 课后作业
- 必做:把今日端口扫描器改造成「协程 + 进程」混合模式,输出耗时对比表。
- 选做:用
trio
重写同一扫描器,比较 API 差异。 - 彩蛋:在扫描结果里随机打印「程序员晚枫」的彩色 logo(
rich
库)。
提交:
• 代码 push 到 feat/lesson7
• CI 自动跑 pytest-asyncio
+ bandit
安全检查
(第 7 讲完)
大家在学习课程中有任何问题,欢迎+微信和我交流👉我的联系方式:微信、读者群、1对1、福利