当前位置:网站首页>Co process, asyncio, asynchronous programming
Co process, asyncio, asynchronous programming
2022-06-28 07:37:00 【Courageous steak】
List of articles
1 coroutines
The coroutine is not provided by the operating system , Provided by programmers ( User state context switching technology )
Coinciding (Coroutine), It can also be called a microthread , It's a context switch technology in user mode . In short , In fact, code blocks are switched and executed through a thread .
Several methods of realizing collaborative process :
- greenlet、 Early modules
- yield keyword
- asynco Decorator (py3.4)
- async、await keyword (py3.5)( recommend )
The significance of synergy
In a thread , If you encounter IO Waiting time , Threads don't wait , Use your spare time to do other things .
2 Asynchronous programming
3.1 The event loop
Understanding micro is an endless cycle , To detect and execute some code
import asyncio
# Generate or get an event loop
loop = asyncio.get_event_loop()
# Put the task on Task list
loop.run_until_complete( Mission )
3.2 async
Coroutines function : When defining a function async def Function name
Coroutine object : Execute the coprogram function () Get the collaboration object
# Coroutine object
async def func():
pass # Content not executed
# Coroutine object
result = func()
Be careful : Execute the coroutine function to create the love coroutine object , Function internal code will not execute
Event loop handler internal code
import asyncio
# Coroutine object
async def func():
pass # Content not executed
# Coroutine object
result = func()
# Add event , Help execute function internal code py3.4
#loop = asyncio.get_event_loop()
#loop.run_until_complete(result)
# py3.7
asycio.run(result)
3.3 await
await + Can wait for the object ( Coroutine object 、Future、Task)
await Is to wait for the value of the object to get the result, and then continue to move forward
Case a :
import asyncio
async def func():
print("666")
# Wait here 2 second , There are other tasks to perform other tasks , Then continue to execute backward
res = await asyncio.sleep(2)
print(" end ", res)
asyncio.run(func())
Case 2 :
import asyncio
async def others():
print("start")
await asyncio.sleep(2)
print("end")
return " Return value "
async def func():
print(" Execute the internal code of the coroutine function ")
# encounter IO Operation suspends the current orchestration ( Mission ), etc. IO After the operation is completed, continue to execute .
# When the current schedule is suspended , The event loop can be used to execute other coroutines ( Mission )
res = await others()
print("IO End of request , The result is :", res)
asyncio.run(func())
Case three
import asyncio
async def others():
print("start")
await asyncio.sleep(2)
print("end")
return " Return value "
async def func():
print(" Execute the internal code of the coroutine function ")
# encounter IO Operation suspends the current orchestration ( Mission ), etc. IO After the operation is completed, continue to execute .
# When the current schedule is suspended , The event loop can be used to execute other coroutines ( Mission )
res1 = await others()
print("IO End of request , The result is :", res1)
res2 = await others()
print("IO End of request , The result is :", res2)
asyncio.run(func())
3.4 Task object
py3.7
Add multiple tasks to the event loop
Task For concurrent scheduling coroutines , adopt
asyncio.create_task( Coroutine object )The way to create love for you Task object , This allows the coroutine to join the event loop and wait for the scheduled execution . Besides usingasyncio.create_task()Function , You can also use lower levelloop_create_task()orensure_future()function . Manual instantiation is not recommended Task object .
Reference address :
https://www.bilibili.com/video/BV1dD4y127bD
边栏推荐
- XML serialization backward compatible
- LLVM 与 Clang
- Top 25 most popular articles on vivo Internet technology in 2021
- "Three routines" of digital collection market
- Ice - resources
- ABAP 技能树
- Mysql57 zip file installation
- ES6 use of return in arrow function
- [thanos source code analysis series]thanos query component source code analysis
- Practice of traffic recording and playback in vivo
猜你喜欢

Design and implementation of spark offline development framework

阿里云服务器创建快照、回滚磁盘

Cloud native (to be updated)

No suspense about the No. 1 Internet company overtime table

本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献

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

8 张图 | 剖析 Eureka 的首次同步注册表

golang gin框架进行分块传输

ES6 use of return in arrow function

Application and Optimization Practice of redis in vivo push platform
随机推荐
Kubelet garbage collection (exiting containers and unused images) source code analysis
Kubernetes deploys a secret pit where thanos ruler sends repeated alarms
Encyclopedia of scala operators
R language hitters data analysis
Construction and exploration of vivo database and storage platform
What is EC blower fan?
自动化测试的生命周期是什么?
Investment transaction and settlement of the fund
HJ字符串排序
异或的应用。(提取出数字中最右侧的1,面试中经常用的到)
Hack the box:routerspace
HJ整数与IP地址间的转换
R 语言 Hitters 数据分析
HJ成绩排序
GoLand IDE and delve debug Go programs in kubernetes cluster
R 语言绘制 动画气泡图
flutter 实现摇一摇功能
OPC 协议认识
Design and implementation of spark offline development framework
Leetcode learning records