异步函数与异步生成器

异步函数介绍

定义:使用 async def 关键字定义的函数,可以暂停执行并在稍后恢复

特点:函数内部可以使用 await 关键字等待其他异步操作完成

返回值:调用时返回协程对象(coroutine),而不是直接执行函数体

性能方面:

  • I/O 密集型:异步并发优势明显
  • CPU 密集型:对于计算密集型任务,异步并不能带来性能提升

其它:避免在异步函数中使用阻塞操作,如 time.sleep(),使用异步版本的操作,如 await asyncio.sleep()

定义

复制代码
async def function_name(parameters):
    # 异步函数体
    await some_async_operation()
    return result

定义要点

  • 使用 async def 替代普通函数的 def
  • 函数内部可以使用 await 关键字
  • 可以使用 return 返回值

调用

在异步环境中调用

  • 使用 await:在另一个异步函数中使用 await function_name()
  • 返回协程对象:直接调用 function_name() 返回协程对象

在同步环境中调用

  • 使用 asyncio.run():asyncio.run(function_name())
  • 创建事件循环:手动创建和管理事件循环

示例

同步环境中调用:asyncio.run

示例:

复制代码
async def hello():
    print("全栈测试笔记")
    return "qzcsbj"


res = hello()
print(res, type(res))

输出结果

复制代码
<coroutine object hello at 0x0000023CA3CA5B40> <class 'coroutine'>
<sys>:0: RuntimeWarning: coroutine 'hello' was never awaited

上面直接调用异步函数hello()会返回一个协程对象,而不是执行函数

修改:asyncio.run()是运行异步函数的标准方式

复制代码
import asyncio


async def hello():
    print("全栈测试笔记")
    return "qzcsbj"


res = hello()
print(res, type(res))
res2 = asyncio.run(res)
print(res2, type(res2))

输出结果:

复制代码
<coroutine object hello at 0x00000216F8162680> <class 'coroutine'>
全栈测试笔记
qzcsbj <class 'str'>

优化

复制代码
import asyncio


async def hello():
    print("全栈测试笔记")
    return "qzcsbj"


if __name__ == "__main__":
    res = hello()
    print(res, type(res))
    res2 = asyncio.run(res)
    print(res2, type(res2))

执行流程:

  • asyncio.run(hello()) 直接启动事件循环
  • 直接执行 hello() 函数并返回结果
  • 简洁的单函数执行模
异步环境中调用:await
复制代码
import asyncio


async def hello():
    print("全栈测试笔记")
    return "qzcsbj"


async def call_hello():
    res = hello()
    print(res, type(res))
    res2 = await res  # await res等价于await hello()
    print(res2, type(res2))


if __name__ == "__main__":
    # call_hello()  # 报错:coroutine 'call_hello' was never awaited call_hello()
    asyncio.run(call_hello())

输出结果:

复制代码
<coroutine object hello at 0x0000023816222680> <class 'coroutine'>
全栈测试笔记
qzcsbj <class 'str'>

执行流程:

  • asyncio.run(call_hello()) 启动事件循环
  • call_hello() 内部先获取 hello() 的协程对象
  • 通过 await 等待协程执行完成
  • 演示了协程对象的创建和等待过程

异步生成器

参考:https://www.cnblogs.com/uncleyong/p/6208547.html

相关推荐
Java后端的Ai之路16 小时前
【Python 教程15】-Python和Web
python
Coder个人博客17 小时前
Linux6.19-ARM64 mm mmu子模块深入分析
大数据·linux·车载系统·系统架构·系统安全·鸿蒙系统
子兮曰17 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
冬奇Lab18 小时前
一天一个开源项目(第15篇):MapToPoster - 用代码将城市地图转换为精美的海报设计
python·开源
吴仰晖18 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神18 小时前
github发布pages的几种状态记录
前端
剩下了什么18 小时前
MySQL JSON_SET() 函数
数据库·mysql·json
山峰哥19 小时前
数据库工程与SQL调优——从索引策略到查询优化的深度实践
数据库·sql·性能优化·编辑器
较劲男子汉19 小时前
CANN Runtime零拷贝传输技术源码实战 彻底打通Host与Device的数据传输壁垒
运维·服务器·数据库·cann
java搬砖工-苤-初心不变19 小时前
MySQL 主从复制配置完全指南:从原理到实践
数据库·mysql