python 中的 async 和 await
最编程
2024-04-25 14:12:33
...
python中的async和await
在 Python 中,async
和 await
是用于编写异步代码的关键语法元素。它们通常与 asyncio
库一起使用,该库是 Python 标准库的一部分,用于编写并发代码。
异步编程
异步编程是一种编程范式,它允许代码块在没有阻塞其他代码块的情况下运行。在传统的同步编程中,当一个任务需要等待(如 I/O 操作)时,它会暂停执行,直到操作完成。这会导致 CPU 空闲,因为它在等待 I/O 完成。
异步编程通过使用非阻塞 I/O 来解决这个问题。当一个任务需要等待时,它会释放 CPU,让其他任务运行,而不是让整个程序暂停。
async
和 await
-
async
:在 Python 中,你可以在函数前面添加async
关键字来定义一个异步函数。一个异步函数返回一个asyncio.Future
对象。async def hello(): print('Hello, world!')
-
await
:await
关键字用于等待一个异步操作的完成。它通常与异步函数一起使用,但它也可以用于等待asyncio.Future
对象。async def main(): print('Hello, world!') await hello()
示例
下面是一个简单的异步函数示例,它使用 async
和 await
:
import asyncio
async def hello():
print('Hello, world!')
await asyncio.sleep(1)
print('Hello again!')
async def main():
print('Starting main coroutine')
await hello()
print('Finished main coroutine')
# 运行主异步函数
asyncio.run(main())
在这个示例中,main
函数是一个异步函数,它等待 hello
函数完成。hello
函数使用 await asyncio.sleep(1)
来模拟一个耗时的操作。asyncio.run(main())
启动主异步函数,并等待它完成。
注意
-
async
和await
不能用在同步函数中。 -
await
只能用在async
函数中。 -
asyncio.Future
是一个可以等待的异步对象。
异步编程可以提高程序的性能,特别是在处理 I/O 密集型任务时。它通过避免在 I/O 操作上阻塞,从而允许程序同时处理多个任务。