并发编程是提升程序性能的重要手段,而 Python 的协程(Coroutine)为编写高并发代码提供了一种优雅、高效的解决方案。本文将从零开始,带你深入理解 Python 协程的演进历程、核心机制和实战技巧。在传统的并发编程中,我们通常使用多线程或多进程。然而,它们各有痛点:
- 多线程受限于全局解释器锁(GIL),CPU 密集型任务无法真正并行;线程切换开销大;共享内存需要复杂的锁机制。
- 多进程
协程则提供了一种轻量级的并发模型。它在单线程内通过协作式调度实现多任务并发,开销极小,特别适合 I/O 密集型任务(如网络请求、文件读写、数据库查询)。
协程的“前身”——生成器
Python 的协程并非一蹴而就,它经历了从生成器(Generator)到协程的演变。理解生成器是理解协程的基础。
1.1 生成器:惰性序列
生成器是 Python 中一种特殊类型的迭代器,使用 yield 关键字定义。它可以在函数执行过程中“暂停”并返回一个值,然后在下次调用时从暂停处继续执行。
defcount_down(n):
while n > 0:
yield n
n -= 1
for i in count_down(5):
print(i)
# 输出: 5 4 3 2 1
1.2 增强生成器:send() 和 throw()
Python 2.5 为生成器增加了 send() 和 throw() 方法,让调用方可以向生成器内部传递数据,使生成器不仅可以“产出”数据,还能“接收”数据,这为协程奠定了基础。
defecho():
whileTrue:
received = yield
print(f"Received: {received}")
coro = echo()
next(coro) # 启动生成器,执行到第一个 yield
coro.send("Hello") # 发送数据给生成器
coro.send("World")
⚠️ 注意:调用 send() 前必须先用 next() 或 send(None) 启动生成器,使其执行到第一个 yield 表达式。
1.3 从生成器到协程
生成器在暂停时保留了函数的状态(局部变量、程序计数器等),这使得它天生适合作为协程的载体。但生成器主要用于迭代,而协程更关注任务间的协作切换,因此 Python 3.4 引入了专门的 asyncio 模块和 @asyncio.coroutine 装饰器,将生成器提升为协程。不过这种方式略显笨拙,直到 Python 3.5 引入了 async/await 语法,协程才真正成为一等公民。
async/await——协程的现代语法
async/await 是 Python 3.5 引入的正式协程语法,它让协程的定义和使用变得直观、简洁。
2.1 定义协程函数
使用 async def 定义的函数称为协程函数,调用它不会立即执行,而是返回一个协程对象。
import asyncio
asyncdefhello():
print("Hello")
await asyncio.sleep(1) # 模拟 I/O 等待
print("World")
2.2 await 关键字
await 用于等待一个可等待对象(如协程、Future、Task)完成。在 await 处,当前协程会“挂起”,让事件循环执行其他任务。
asyncdefmain():
await hello()
# 运行协程
asyncio.run(main())
2.3 协程的特性
- 单线程所有协程运行在同一个线程中,无需考虑线程安全问题。
- 协作式协程主动让出控制权(通过
await),而不是被抢占。 - 轻量
事件循环——协程的“调度器”
事件循环是协程运行的核心驱动。它负责管理所有协程的执行顺序,包括启动、挂起、恢复和完成。
3.1 获取事件循环
在 Python 3.7+ 中,推荐使用 asyncio.run() 自动创建和关闭事件循环。底层的 asyncio.get_event_loop() 也可用,但需注意不同平台的差异。
import asyncio
asyncdefmain():
print("Running")
asyncio.run(main()) # 自动创建并运行事件循环
3.2 创建任务
要将协程提交到事件循环并实现并发执行,需要将协程包装为 Task。asyncio.create_task() 是推荐方式。
asyncdeftask(name, seconds):
await asyncio.sleep(seconds)
print(f"Task {name} done")
asyncdefmain():
task1 = asyncio.create_task(task("A", 2))
task2 = asyncio.create_task(task("B", 1))
await task1
await task2
asyncio.run(main())
💡 create_task vs ensure_future:create_task 是 Python 3.7+ 推荐的方式,只能在协程内部使用。ensure_future 更通用,可接受协程、Future 等对象。
并发执行模式
4.1 asyncio.gather() —— 并发执行多个协程
asyncdeffetch(url):
await asyncio.sleep(1) # 模拟网络请求
returnf"Data from {url}"
asyncdefmain():
results = await asyncio.gather(
fetch("url1"),
fetch("url2"),
fetch("url3")
)
print(results)
asyncio.run(main())
gather() 会并发执行所有协程,并等待它们全部完成,返回结果列表。如果某个协程抛出异常,默认会取消其他协程(可通过 return_exceptions=True 控制)。
4.2 asyncio.wait() —— 更精细的控制
asyncdefmain():
tasks = [asyncio.create_task(fetch(f"url{i}")) for i inrange(5)]
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
# done 包含已完成的任务,pending 包含未完成的
for task in done:
print(task.result())
return_when 参数控制返回时机:
FIRST_COMPLETEDFIRST_EXCEPTIONALL_COMPLETED
4.3 asyncio.as_completed() —— 按完成顺序处理
asyncdefmain():
tasks = [fetch(f"url{i}") for i inrange(5)]
for coro in asyncio.as_completed(tasks):
result = await coro
print(f"Got: {result}")
as_completed 返回一个迭代器,每次产生一个完成的任务,适合需要尽快处理结果的场景。
同步原语
虽然协程是单线程的,但在某些情况下仍需同步机制,例如保护共享资源或协调多个协程的执行顺序。
5.1 锁(Lock)
import asyncio
lock = asyncio.Lock()
shared_resource = 0
asyncdefmodify():
global shared_resource
asyncwith lock:
# 临界区
temp = shared_resource
await asyncio.sleep(0.1) # 模拟耗时操作
shared_resource = temp + 1
asyncdefmain():
await asyncio.gather(*(modify() for _ inrange(10)))
print(shared_resource) # 输出 10
asyncio.run(main())
5.2 事件(Event)
event = asyncio.Event()
asyncdefwaiter():
print("Waiting for event...")
await event.wait()
print("Event triggered!")
asyncdefsetter():
await asyncio.sleep(2)
event.set()
print("Event set")
asyncdefmain():
await asyncio.gather(waiter(), setter())
5.3 队列(Queue)
异步队列非常适合生产者-消费者模式。
import asyncio
asyncdefproducer(queue):
for i inrange(5):
await queue.put(f"item-{i}")
await asyncio.sleep(0.5)
await queue.put(None) # 结束信号
asyncdefconsumer(queue):
whileTrue:
item = await queue.get()
if item isNone:
break
print(f"Consumed: {item}")
asyncdefmain():
queue = asyncio.Queue(maxsize=10)
await asyncio.gather(producer(queue), consumer(queue))
asyncio.run(main())
异步上下文管理器与异步迭代器
6.1 异步上下文管理器
使用 async with 管理需要异步操作的上下文,例如异步文件操作或数据库连接。
classAsyncResource:
asyncdef__aenter__(self):
await asyncio.sleep(0.1)
returnself
asyncdef__aexit__(self, exc_type, exc_val, exc_tb):
await asyncio.sleep(0.1)
asyncdefmain():
asyncwith AsyncResource() as res:
print("Using resource")
6.2 异步迭代器
使用 async for 迭代异步生成的数据流。
asyncdefasync_range(n):
for i inrange(n):
await asyncio.sleep(0.1)
yield i
asyncdefmain():
asyncfor i in async_range(5):
print(i)
实战——构建异步 Web 爬虫
下面我们将理论付诸实践,构建一个并发爬虫,批量抓取多个网页内容。
import asyncio
import aiohttp
asyncdeffetch_url(session, url):
try:
asyncwith session.get(url) as response:
returnawait response.text()
except Exception as e:
returnf"Error fetching {url}: {e}"
asyncdefmain():
urls = [
"https://httpbin.org/get",
"https://httpbin.org/ip",
"https://httpbin.org/user-agent",
"https://httpbin.org/headers"
]
asyncwith aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for url, content inzip(urls, results):
print(f"Fetched {url}: {len(content)} bytes")
asyncio.run(main())
💡 学习要点:aiohttp 是异步 HTTP 客户端库,与 asyncio 完美配合。async with 管理会话和请求,确保资源正确释放。
多练习,理解异步,愿你的程序不再因 I/O 阻塞而等待! 🚀