异步编程核心概念
在构建高并发应用时,理解 Python 的异步机制至关重要。它允许程序在等待 I/O 操作完成时继续执行其他任务,从而显著提升效率。
什么是异步编程
异步编程通过非阻塞操作提高执行效率。当程序遇到网络请求或文件读写等耗时操作时,无需挂起整个线程,而是切换到其他任务。这种方式减少了资源消耗,简化了代码结构。
常见应用场景包括网络通信(HTTP、WebSocket)、大文件操作以及数据库查询。
协程的定义与使用
协程(Coroutine)是轻量级的线程,支持暂停和恢复。在 Python 中,使用 async def 关键字定义协程。
import asyncio
async def hello():
print('Hello, World!')
await asyncio.sleep(1)
print('Hello again!')
asyncio.run(hello())
这里我们直接调用 asyncio.run() 启动事件循环并运行协程。注意 await 关键字,它表示在此处暂停当前协程,让出控制权给事件循环。
协程的并发执行
我们可以同时运行多个协程,使用 asyncio.gather 来收集结果:
import asyncio
async def count():
print('Counting...')
await asyncio.sleep(1)
print('Counted!')
async def main():
await asyncio.gather(count(), count(), count())
asyncio.run(main())
任务调度与管理
创建与取消任务
使用 asyncio.create_task 可以将协程包装为任务对象,便于管理生命周期。如果需要提前终止某个任务,可以调用 task.cancel()。
import asyncio
async def hello():
try:
print()
asyncio.sleep()
()
asyncio.CancelledError:
()
():
task = asyncio.create_task(hello())
asyncio.sleep()
task.cancel()
:
task
asyncio.CancelledError:
()
asyncio.run(main())


