一、术语
1、coroutine func:用async def定义的函数
2、coroutine object:调用coroutine func生成
3、task:coroutine object在eventloop即为task
4、await一个coroutine object就会将此object注册为task,并且此task在eventloop需要优先执行,然后返回函数的返回值
5、async模式:eventloop控制task执行,对应sync模式,进入的唯一入口是asyncio.run(),其参数是coroutine object
6、eventloop开启task后,只有task函数执行完成或者await之后才能再次拿到执行权,故此协程不存在数据竞争
二、代码
1
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f'start at {time.strftime('%X')}')
await say_after(1, 'hello') # ,
'''
1、corountine对象变成task加入eventloop
2、在eventloop中此task优先于调用者task(此处为main)
3、yield出去,eventloop重新得到控制权,并且立即执行刚创建的task(此处为say_after)
4、say_after执行完毕后返回函数的返回值
'''
await say_after(2, 'world')
print(f'end at {time.strftime('%X')}')
corountine_object = main()
asyncio.run(corountine_object)
2
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
return f'{what}-{delay}'
async def main():
task1 = asyncio.create_task(say_after(2, 'hello'))
task2 = asyncio.create_task(say_after(1, 'world'))
print(f'start at {time.strftime('%X')}')
ret1 = await task1
ret2 = await task2
print(ret1)
print(ret2)
print(f'end at {time.strftime('%X')}')
corountine_object = main()
asyncio.run(corountine_object)
3
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
return f'{what}-{delay}'
async def main():
task1 = asyncio.create_task(say_after(2, 'hello'))
task2 = asyncio.create_task(say_after(1, 'world'))
print(f'start at {time.strftime('%X')}')
ret = await asyncio.gather(say_after(2, 'hello'), say_after(1, 'world'))
'''
1、gather参数可以是coroutine object、task、或者futher
2、gather返回futher
3、await futher和await coroutine object或者task类似
'''
print(ret)
print(f'end at {time.strftime('%X')}')
corountine_object = main()
asyncio.run(corountine_object)