当前位置:网站首页>协程、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
边栏推荐
猜你喜欢

Resizing node of rediscluster cluster cluster mode

Alibaba cloud server creates snapshots and rolls back disks

kubelet垃圾(退出的容器和未使用的镜像)回收源码分析

以动态规划的方式求解最长回文子串

ABAP skill tree

HJ质数因子

Section VI UART of zynq

Redis implements distributed locks

Introduction and several months' experience of extending the solution thanos of Prometheus

mysql57 zip文件安装
随机推荐
Drawing animated bubble chart with R language
Ice - resources
Is it reliable to register and open an account for stock speculation? Is it safe?
Design and practice of vivo sensitive word matching system
Introduction and several months' experience of extending the solution thanos of Prometheus
Solving the longest palindrome substring by dynamic programming
Modifying MySQL user name root under Linux
Ice, protobuf, thrift -- Notes
Spark 离线开发框架设计与实现
Resizing node of rediscluster cluster cluster mode
卸载重装最新版mysql数据库亲测有效
linux下修改mysql端口号
云原生(待更新)
Force buckle 515 Find the maximum value in each tree row
腾讯下半年继续裁员,所有事业群至少缩减 10%,对此你怎么看?关注者
Kubernetes cluster lossless upgrade practice
Safety training is the greatest benefit for employees! 2022 induction safety training for new employees
Design and implementation of spark offline development framework
Understanding of OPC protocol
Llvm and clang