当前位置:网站首页>协程、asyncio、异步编程
协程、asyncio、异步编程
2022-06-28 07:36:00 【有勇气的牛排】
1 协程
协程不是由操作系统提供,由程序员人为提供(用户态上下文切换技术)
协称(Coroutine),也可以被称为微线程,是一种用户态内的上下文切换技术。简而言之,其实就是通过一个线程实现代码块相互切换执行。
实现协程的几种方法:
- greenlet、早期模块
- yield关键字
- asynco装饰器(py3.4)
- async、await关键字(py3.5)(推荐)
协程意义
在一个线程中,如果遇到IO等待时间,线程不会等,利用空闲的时间在去干其他事。
2 异步编程
3.1 事件循环
理解微一个死循环,去检测并执行某些代码
import asyncio
# 生成或获取一个事件循环
loop = asyncio.get_event_loop()
# 将任务放到 任务列表
loop.run_until_complete(任务)
3.2 async
协程函数:定义函数的时候async def 函数名
协程对象:执行协程函数()得到协程对象
# 协程对象
async def func():
pass # 内容不执行
# 协程对象
result = func()
注意:执行协程函数创建爱协程对象,函数内部代码不会执行
事件循环处理函数内部代码
import asyncio
# 协程对象
async def func():
pass # 内容不执行
# 协程对象
result = func()
# 添加事件,帮助执行函数内部代码 py3.4
#loop = asyncio.get_event_loop()
#loop.run_until_complete(result)
# py3.7
asycio.run(result)
3.3 await
await + 可等待对象(协程对象、Future、Task)
await就是等待对象的值得到结果之后在继续往下走
案例一:
import asyncio
async def func():
print("666")
# 这里等待2秒,有其他任务执行其他任务,然后继续向后执行
res = await asyncio.sleep(2)
print("结束", res)
asyncio.run(func())
案例二:
import asyncio
async def others():
print("start")
await asyncio.sleep(2)
print("end")
return "返回值"
async def func():
print("执行协程函数内部代码")
# 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行。
# 当前协程挂起时,事件循环可以去执行其他协程(任务)
res = await others()
print("IO请求结束,结果为:", res)
asyncio.run(func())
案例三
import asyncio
async def others():
print("start")
await asyncio.sleep(2)
print("end")
return "返回值"
async def func():
print("执行协程函数内部代码")
# 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行。
# 当前协程挂起时,事件循环可以去执行其他协程(任务)
res1 = await others()
print("IO请求结束,结果为:", res1)
res2 = await others()
print("IO请求结束,结果为:", res2)
asyncio.run(func())
3.4 Task对象
py3.7
在事件循环中添加多个任务
Task用于并发调度协程,通过
asyncio.create_task(协程对象)的方式创建爱你Task对象,这样可以让协程加入事件循环中等待被调度执行。除了使用asyncio.create_task()函数以外,还可以用更低层级的loop_create_task()或ensure_future()函数。不建议手动实例化Task对象。
参考地址:
https://www.bilibili.com/video/BV1dD4y127bD
边栏推荐
- Real time database - Notes
- 分析 NFT 项目的 5 个指标
- 代码提交规范
- 推荐系统系列精讲(第五讲): 排序模型的调优实践
- PLC -- 笔记
- R language drawing ggplot2 seasonal graph
- SQL statement optimization steps (1)
- 一个小工具可以更快的写爬虫
- Practice and exploration of vivo live broadcast application technology
- Source code analysis of kubernetes' process of deleting pod
猜你喜欢
随机推荐
Evolution of vivo push platform architecture
Path alias specified in vite2.9
7-1 懂的都懂
Leetcode+ 66 - 70 high precision, two sub topics
[ thanos源码分析系列 ]thanos query组件源码简析
Rediscluster cluster mode capacity expansion node
股票炒股注册开户靠谱吗?安全吗?
mysql57 zip文件安装
R language ggmap
okcc呼叫中心没有电脑的坐席能不能开展工作?
Spark 离线开发框架设计与实现
Mysql8.0和Mysql5.0访问jdbc连接
Evaluation of inverse Polish expression < difficulty coefficient >
代码提交规范
Code submission specification
Flutter realizes the function of "shake"
Static resource compression reduces bandwidth pressure and increases access speed
A gadget can write crawlers faster
kubernetes删除pod的流程的源码简析
R 和 rgl 绘制 3D 结









