Home >Backend Development >Python Tutorial >What are the implementation methods of Python coroutines?

What are the implementation methods of Python coroutines?

WBOY
WBOYforward
2023-04-23 10:22:061778browse

1. 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]

1.1greenlet implements coroutine

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

1.2yield keyword implements coroutine

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

1.3 Use the asyncio module to implement coroutines

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())

1.4async & await keywords to implement coroutines Cheng

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)

2. Coroutine meaning

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

3. Asynchronous programming

3.1 Time loop

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(任务)

3.2 Case

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)

3.3await keyword

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete