代码
import asyncio import time async def first_fun(delay): print('开始执行 first_fun 函数。') await asyncio.sleep(delay) print('first_fun 函数执行结束。') return delay async def second_fun(delay): print('开始执行 second_fun 函数。') await asyncio.sleep(delay) print('second_fun 函数执行结束。') return delay async def main(): print(f"started at {time.strftime('%X')}") first = asyncio.create_task(first_fun(5)) print('=============') second = asyncio.create_task(second_fun(4)) # await first # await second print('=============') print(f"finished at {time.strftime('%X')}") asyncio.run(main())
执行结果
started at 13:35:37 ============= ============= finished at 13:35:37 开始执行 first_fun 函数。 开始执行 second_fun 函数。
代码2
import asyncio import time async def first_fun(delay): print('开始执行 first_fun 函数。') await asyncio.sleep(delay) print('first_fun 函数执行结束。') return delay async def second_fun(delay): print('开始执行 second_fun 函数。') await asyncio.sleep(delay) print('second_fun 函数执行结束。') return delay async def main(): print(f"started at {time.strftime('%X')}") first = asyncio.create_task(first_fun(5)) print('=============') second = asyncio.create_task(second_fun(4)) await first await second print('=============') print(f"finished at {time.strftime('%X')}") asyncio.run(main())
执行结果
started at 13:37:20 ============= 开始执行 first_fun 函数。 开始执行 second_fun 函数。 second_fun 函数执行结束。 first_fun 函数执行结束。 ============= finished at 13:37:25
结论
asyncio.create_task():就相当于开启了一个线程。 await :相当用线程的 join,等待协程的运行结束,再继续运行之后的代码。
更多asyncio教程 https://blog.csdn.net/songjinxaing/article/details/103883210