异步设计模式
生产者消费者、异步上下文管理器、异步迭代器、信号量限流
异步设计模式
异步编程不只是 await——掌握生产者消费者、信号量限流、异步上下文管理器才算入门。
学完本章你将: 掌握生产者消费者、异步上下文、异步迭代器、信号量限流。
生产者消费者
python
import asyncio
async def producer(queue):
for i in range(5):
await asyncio.sleep(0.5)
await queue.put(i)
print(f"生产: {i}")
await queue.put(None) # 终止信号
async def consumer(queue):
while True:
item = await queue.get()
if item is None:
break
await asyncio.sleep(1)
print(f"消费: {item}")
async def main():
queue = asyncio.Queue(maxsize=3)
await asyncio.gather(producer(queue), consumer(queue))
信号量限流
python
# 限制同时发起的请求数
sem = asyncio.Semaphore(3) # 最多 3 个并发
async def fetch_with_limit(url):
async with sem: # 获取信号量——超过 3 个就等待
return await fetch(url)
tasks = [fetch_with_limit(url) for url in urls]
results = await asyncio.gather(*tasks)
异步上下文管理器
python
class AsyncResource:
async def __aenter__(self):
await asyncio.sleep(0.1)
print("资源已获取")
return self
async def __aexit__(self, *args):
await asyncio.sleep(0.1)
print("资源已释放")
async def main():
async with AsyncResource() as r:
print("使用资源")