Python异步编程asyncio深入理解
2026/5/28 21:27:33 网站建设 项目流程

Python异步编程:asyncio深入理解

一、核心概念

asyncio 基于事件循环调度协程:
- 协程(coroutine):async def 定义的异步函数
- 任务(Task):协程的并发调度包装器
- Future:异步操作的最终结果
- 事件循环(Event Loop):调度和执行异步任务


二、协程基础

import asyncio

async def fetch(url, delay):
await asyncio.sleep(delay)
return f"{url} 的数据"

async def main():
result = await fetch("api/users", 2)
print(result)

asyncio.run(main())

await 暂停当前协程,将控制权交还事件循环。


三、并发执行

# asyncio.gather
async def main():
results = await asyncio.gather(
fetch("api/users", 2),
fetch("api/posts", 1),
fetch("api/comments", 3),
)

# asyncio.create_task
async def main():
task1 = asyncio.create_task(fetch("api/users", 2))
task2 = asyncio.create_task(fetch("api/posts", 1))
result1 = await task1
result2 = await task2

# TaskGroup (Python 3.11+)
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch("api/users", 2))
t2 = tg.create_task(fetch("api/posts", 1))


四、异步迭代器

class AsyncCounter:
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.end:
raise StopAsyncIteration
await asyncio.sleep(0.5)
self.current += 1
return self.current - 1

async for num in AsyncCounter(0, 5):
print(num)


五、超时与取消

async def main():
try:
result = await asyncio.wait_for(slow_op(), timeout=3.0)
except asyncio.TimeoutError:
print("超时")

task.cancel() # 取消任务


六、异步同步原语

- asyncio.Lock
- asyncio.Semaphore(限制并发数)
- asyncio.Queue(生产者-消费者)

semaphore = asyncio.Semaphore(5)

async def limited_task(url):
async with semaphore:
return await fetch(url, 1)


七、实际应用

import aiohttp

async def fetch_all(urls):
async with aiohttp.ClientSession() as session:
tasks = [session.get(url) for url in urls]
return await asyncio.gather(*tasks)

with ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(pool, blocking_func)

总结:asyncio 通过单线程事件循环实现高并发IO,避免了多线程的锁竞争。await 的暂停/恢复机制是理解的关键。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询