We covered coroutines in the last article, but now let’s formally introduce the basics of coroutines.
1. How to define coroutines? The essence of a coroutine is still a function, it’s an asynchronous function, you just add async to a normal function, so the essence of a coroutine is an asynchronous function;
2. How do coroutines work? Coroutines do not run when used directly as normal functions:
async def paly_game(name:str):
print(name)
paly_game('kpl')
Copy the code
Running results:
RuntimeWarning: coroutine 'paly_game' was never awaited
paly_game('kpl')
Copy the code
There are three ways to run coroutines in existing libraries: (1) asyncio.run
async def paly_game(name:str):
print(name)
asyncio.run(paly_game('kpl'))
Copy the code
Async functions/coroutines call coroutines with await. We can look at an example:
Async def paly_game(name: STR): print(name) async def play(): await paly_game(' KPL ')# call paly_game asyncio.run(play())Copy the code
Note that await must be used inside the function, otherwise an error will be reported:
async def paly_game(name:str):
print(name)
await paly_game()
Copy the code
Running results:
await paly_game()
^
SyntaxError: 'await' outside function
Copy the code
(3) asyncio.create_task(asynchronous function/coroutine), then run the task
async def paly_game(name:str):
print(name)
async def play():
task=asyncio.create_task(paly_game('kpl'))
await task
asyncio.run(play())
Copy the code
Await can be followed by coroutine or coroutine task. What is the difference between the two? Let’s take a look at direct coroutines:
import asyncio
import time
async def paly_game(name:str,t:int):
await asyncio.sleep(t)
print(name)
async def play():
start=time.time()
await paly_game('kpl',2)
await paly_game('kpl',3)
print('spend total time is {}'.format(time.time()-start))
asyncio.run(play())
Copy the code
Running results:
KPL KPL spend total time is 5.016455888748169Copy the code
We find that it looks like the coroutine doesn’t work at all, or 3+2=5 seconds. In fact, scheduling-like coroutines occur only when task is used:
import asyncio
import time
async def paly_game(name:str,t:int):
await asyncio.sleep(t)
print(name)
async def play():
start=time.time()
task1=asyncio.create_task(paly_game('kpl',2))
task2 = asyncio.create_task(paly_game('kpl', 3))
await task1
await task2
print('spend total time is {}'.format(time.time()-start))
asyncio.run(play())
Copy the code
Running results:
KPL KPL spend total time is 2.995018243789673Copy the code
Now our coroutine will kick in.