Home >Backend Development >Python Tutorial >What are the implementation methods of Python coroutines?
Coroutines are not provided by computers. Computers only provide: processes and threads. Coroutine is an artificially created micro-process for user mode switching, using one thread to switch back and forth between multiple processes
Several methods of implementing coroutine
greenlet : Early module
yield keyword: can save code, save state
asyncio decorator (3.4)
async, await keywords (3.5) [Recommended]
pip install greenlet from greenlet import greenlet def fun1(): gre2.switch()#切换到fun2 pass def fun2(): gre1.switch()#切换到fun1 pass gre1 = greenlet(func1) gre2 = greenlet(func2) gre1.switch()#先去执行fun1
def func1(): yield 1 yield from func2() yield 2 def func2(): yield 3 yield 4 f1 = func1() for item in f1: print(item,end=" ") #打印结果 1 3 4 2
It can only be used after python3.4 version (no need to install, it is in the standard library)
import asyncio #使用该装饰器装饰后,该函数就是一个协程函数 @asyncio.coroutine def func1(): print(1) #遇到IO操作时,会自动切换到taks中的其他任务函数 yield from asyncio.sleep(2) print(2) @asyncio.coroutine def func2(): print(3) yield from asyncio.sleep(2) print(4) #将两个协程函数封装成一个tasks列表 tasks = [ asyncio.ensure_future(func1()), asyncio.ensure_future(func2()) ] # loop = asyncio.get_event_loop() loop.run_until_complete(func1())
import asyncio #使用该装饰器装饰后,该函数就是一个协程函数 async def func1(): print(1) #遇到IO操作时,会自动切换到tasks中的其他任务函数 await asyncio.sleep(2) print(2) async def func2(): print(3) await asyncio.sleep(2) print(4) #将两个协程函数封装成一个tasks列表 tasks = [ asyncio.ensure_future(func1()), asyncio.ensure_future(func2()) ] loop = asyncio.get_event_loop() loop.run_until_complete(tasks)
If the thread encounters IO waiting time, the thread will not wait stupidly, but will use the idle time to do other things, that is, the process is asynchronous implement.
#协程请求资源使用第三方库aiohttp import aiohttp
Understood as an infinite loop to detect and execute certain codes
#伪代码 任务列表 = [task1,task2...] while True: for 就绪任务 in 可执行任务列表: 执行 for 已完成任务 in 已完成任务列表: 从任务列表中删除 import asyncio #生成一个书简循环 loop = asyncio.get_event_loop() #将任务放到任务列表中 loop.run_until_complete(任务)
Coroutine function,
When defining a function, use async def function name
Coroutine object: Get a coroutine when executing the coroutine function Object
async def func(): pass result = func()
Note: The coroutine object obtained when executing the coroutine function, the code inside the function will not be executed
import asyncio async def func(): print("哈喽") f = func()#协程对象 loop = asyncio.get_event_loop()#创建循环对象 loop.run_until_complete(f)#通过循环对象执行协程对象 #python3.7可以直接 asyncio.run(f)
await waitable object{ Coroutine object, Future object, Task object} (similar to I O waiting)
import asyncio async def func(): print("哈喽") re = await asyncio.sleep(2) print(re) asyncio.run(func())
await is to wait for the value of the object to get the result before continuing to execute downwards
import asyncio async def other(): print("start") await asyncio.sleep(2) print("end") return 1 async def fun(): print("执行协程函数内部代码") #遇到IO操作时会挂起当前协程任务,等IO操作完成后再继续往下执行,当前协程挂起时,时间循环对象可以执行其他协程任务 re = await other() print("IO请求结束,结果为:",re) asyncio.run(func())
Execution result
Execute the internal code of the coroutine function
start
end
The IO request ends, the result is: 1
The above is the detailed content of What are the implementation methods of Python coroutines?. For more information, please follow other related articles on the PHP Chinese website!