当前位置:网站首页>协程、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
边栏推荐
- ABAP skill tree
- Jetpack - defects of livedata component and Countermeasures
- Construction and exploration of vivo database and storage platform
- 2021 programming language ranking summary
- Practice and exploration of vivo live broadcast application technology
- Open62541 import nodeset file directly
- A gadget can write crawlers faster
- Resizing node of rediscluster cluster cluster mode
- linux下修改mysql端口号
- R语言绘制 ggplot2 季节性图
猜你喜欢

Mysql57 zip file installation

Vivo browser rapid development platform practice - Overview

8 figures | analyze Eureka's first synchronization registry

Unity-UI-shadow组件

2021 programming language ranking summary

什么是EC鼓风机(ec blower fan)?

Leetcode learning records

Kubelet garbage collection (exiting containers and unused images) source code analysis

剑指Offer||:链表(简单)

Recommended system series (Lecture 5): Optimization Practice of sorting model
随机推荐
Implementation of commit message standardized control in large projects
Rediscluster cluster mode capacity expansion node
es6箭头函数中return的用法
Devtools implementation principle and performance analysis practice
Kubernetes cluster lossless upgrade practice
Hash slot of rediscluster cluster cluster implementation principle
What should I do if the version is incompatible with the jar package conflict?
2021 VDC: technological architecture evolution of vivo Internet service for 100 million users | PPT download attached
腾讯下半年继续裁员,所有事业群至少缩减 10%,对此你怎么看?关注者
HTTP Caching Protocol practice
Encyclopedia of scala operators
HJ整数与IP地址间的转换
剑指Offer||:链表(简单)
同花顺网上开户安全吗
Unity-UI-shadow组件
Top 25 most popular articles on vivo Internet technology in 2021
Unity UI shadow component
MySQL installation steps - installing MySQL on Linux (3)
Understanding of OPC protocol
Alibaba cloud server creates snapshots and rolls back disks