1.第一种写法
import asyncio from time import time
async def fun(name): print(name, "1========") await asyncio.sleep(3) print(name,"2======") rest = name + '返回值' return rest async def fun_1(name): print(name, "1=================") await asyncio.sleep(3) print(name, '2============') rest = name + '返回值' return rest async def main(): start_time = time() print('main 开始') # task1 = asyncio.create_task(fun('task1')) # task2 = asyncio.create_task(fun('task2')) # task3 = asyncio.create_task(fun_1('task3')) task_list = [ asyncio.create_task(fun('task1'), name='task1'), asyncio.create_task(fun('task2'), name='task2'), asyncio.create_task(fun_1('task3'), name='task3') ] print('main结束') # rest1 = await task1 # rest2 = await task2 # rest3 = await task3 done, pending = await asyncio.wait(task_list, timeout=None) print('done=======', done) end_time = time() print("time_total=====", end_time-start_time) # print(rest1, rest2, rest3) asyncio.run(main())
2.第二种写法
async def fun(name): print(name, "1========") await asyncio.sleep(1) print(name,"2======") rest = name + '返回值' return rest async def fun_1(name): print(name, "1=================") await asyncio.sleep(1) print(name, '2============') rest = name + '返回值' return rest task_list = [ fun("task1"), fun('task2'), fun_1('task3') ] start_time = time() done, pending = asyncio.run(asyncio.wait(task_list)) end_time = time() print('total time=======', end_time-start_time) print('done==', done) print('type====', type(done)) print('pending===', pending) for index, i in enumerate(done): print('index===', index, '\n', 'i======', i, '\n', 'type(i)===', type(i), '\n', 'reult====', i.result(), '\n') end_time = time() print('total time=======', end_time-start_time)