当前位置: 首页 > news >正文

Python 异步编程之 async 和 await

基础知识

在 Python 中,async 和 await 是用于异步编程的关键字,引入了异步/协程(coroutine)的概念。核心思想是通过 协程(Coroutine) 和 事件循环(Event Loop) 实现非阻塞并发,避免线程切换的开销。

异步编程是一种处理并发任务的方式,使得程序能够在等待某些 I/O 操作(如文件读写、网络请求等)的同时继续执行其他任务,而不会发生阻塞

  • 异步(Asynchronous):在异步编程中,程序不会等待某些I/O操作完成,而是继续执行其他任务,待操作完成后再回来处理结果
  • 协程(Coroutine):协程是一种轻量级的线程,可以在执行过程中暂停并让出控制权,然后在需要时恢复执行使用协程可以更有效地利用系统资源,避免线程切换的开销

异步和多线程区别

异步和多线程的区别可参考这篇文章:

一篇文章,搞懂异步和多线程的区别-腾讯云开发者社区-腾讯云 

同步示例

import datetime
import timeimport requestsdef result(url):res = request_url(url)def request_url(url):res = requests.get(url)print(url)time.sleep(2)print("execute_time:", datetime.datetime.now() - start_time)return resdef main():url_list = ["https://www.csdn.net/","https://blog.csdn.net/TomorrowAndTuture/article/details/149402464","https://www.baidu.com/",]task = [result(url) for url in url_list]start_time = datetime.datetime.now()
print(f"start_time:{start_time}\n")
main()
end_time = datetime.datetime.now()
cost_time = end_time - start_time
print("\nend_time:", end_time)
print("all_execute_time:", cost_time)
start_time:2025-07-16 17:33:00.905345https://www.csdn.net/
execute_time: 0:00:02.404500
https://blog.csdn.net/qq_43380180/article/details/111573642
execute_time: 0:00:04.839844
https://www.baidu.com/
execute_time: 0:00:07.543495end_time: 2025-07-16 17:33:08.448840
all_execute_time: 0:00:07.543495

异步示例

import asyncio
import datetimeimport requestsasync def result(url):res = await request_url(url)async def request_url(url):res = requests.get(url)print(url)await asyncio.sleep(2)print("execute_time:", datetime.datetime.now() - start_time)return resasync def main():url_list = ["https://www.csdn.net/","https://blog.csdn.net/TomorrowAndTuture/article/details/149402464","https://www.baidu.com/",]task = [asyncio.create_task(result(url)) for url in url_list]await asyncio.gather(*task)start_time = datetime.datetime.now()
print(f"start_time:{start_time}\n")
asyncio.run(main())
end_time = datetime.datetime.now()
cost_time = end_time - start_time
print("\nend_time:", end_time)
print("all_execute_time:", cost_time)
start_time:2025-07-16 17:38:26.561693https://www.csdn.net/
https://blog.csdn.net/qq_43380180/article/details/111573642
https://www.baidu.com/
execute_time: 0:00:03.136231
execute_time: 0:00:03.963955
execute_time: 0:00:04.945443end_time: 2025-07-16 17:38:31.508156
all_execute_time: 0:00:04.946463

asyncio.create_task() 用于并发执行多个协程任务,而 asyncio.gather() 用于等待多个协程任务的全部完成,并且可以收集执行结果。

关键步骤详解 

  • asyncio.run(coro):启动事件循环并运行协程。
  • asyncio.create_task(coro):将协程包装为 Task,加入事件循环并发执行。
  • asyncio.gather(*coros):并发执行多个协程,返回结果列表。
  • asyncio.sleep(delay):非阻塞等待(模拟 I/O 操作),如果是直接用 time.sleep(delay) 则会产生阻塞等待。
  • 使用 async def 定义协程,用 await 挂起阻塞操作。
  • 通过 asyncio.create_task() 和 asyncio.gather() 实现并发。
  • 避免在 async def 定义的协程中调用阻塞同步代码(比如 time.sleep(delay))。
http://www.dtcms.com/a/285082.html

相关文章:

  • ThreadLocal源码解析
  • Mac OS上docker desktop 替代方案
  • Linux 下按字节分割与合并文件
  • 压力大为啥想吃甜食
  • wireshark的常用用法
  • C++ Lambda 表达式详解:从入门到实战
  • Leetcode 03 java
  • 设备管理系统横评:预警功能、移动端体验、性价比谁更强?
  • PyTorch图像预处理全解析(transforms)
  • SAP-ABAP:SAP的‘cl_http_utility=>escape_url‘对URL进行安全编码方法详解
  • 6 基于STM32单片机的智能家居系统设计(STM32代码编写+手机APP设计+PCB设计+Proteus仿真)
  • 如何从 iPhone 向Mac使用 AirDrop 传输文件
  • 企业网络运维进入 “AI 托管” 时代:智能分析 + 自动决策,让云、网、端一眼看穿
  • 关于用git上传远程库的一些常见命令使用和常见问题:
  • Redis学习-02安装Redis(Ubuntu版本)、开启远程连接
  • ComfyUI 中RAM内存、VRAM显存、GPU 的占用和原理
  • 基于深度学习的图像识别:从零构建卷积神经网络(CNN)
  • 面对微软AD的安全隐患,宁盾身份域管如何设计安全性
  • Python调用父类方法的三种方式详解 | Python面向对象编程教程
  • 【DOCKER】-5 镜像仓库与容器编排
  • 云服务器如何设置防火墙和安全组规则?
  • Java EE进阶3:SpringBoot 快速上手
  • 【Linux】Makefile(二)-书写规则
  • 【原创】【图像算法】高精密电子仪器组装异常检测
  • 力扣119:杨辉三角Ⅱ
  • Cursor出现This model provider doesn’t serve your region解决方案
  • 【调度算法】
  • javaScript中数组常用的函数方法
  • 洛谷 P1601 A+B Problem(高精)
  • 重构比特币在 Sui DeFi 中的角色