通过async定义,并且要在main函数里面await一个或者是多个协程,同前面一样,我可以通过gather或者是wait进行组合,对于有返回值的协程函数,一般就在main里面进行结果的获取。
async def main():
result = asyncio.gether(coro1(),coro2())
asyncio.run(main())
import asyncio
async def hello1():
print("Hello world 01 begin")
await asyncio.sleep(3) # 模拟耗时任务3秒
print("Hello again 01 end")
async def hello2():
print("Hello world 02 begin")
await asyncio.sleep(2) # 模拟耗时任务2秒
print("Hello again 02 end")
async def hello3():
print("Hello world 03 begin")
await asyncio.sleep(4) # 模拟耗时任务4秒
print("Hello again 03 end")
async def main():
await asyncio.gather(hello1(), hello2(), hello3())
asyncio.run(main())
import asyncio
async def hello1(a, b):
print("Hello world 01 begin")
await asyncio.sleep(3) # 模拟耗时任务3秒
print("Hello again 01 end")
return a + b
async def hello2(a, b):
print("Hello world 02 begin")
await asyncio.sleep(2) # 模拟耗时任务2秒
print("Hello again 02 end")
return a - b
async def hello3(a, b):
print("Hello world 03 begin")
await asyncio.sleep(4) # 模拟耗时任务4秒
print("Hello again 03 end")
return a * b
async def main():
results = await asyncio.gather(hello1(10, 5), hello2(10, 5), hello3(10, 5))
for result in results:
print(result)
asyncio.run(main())
注意:
不再需要显式的创建事件循环,因为在启动run函数的时候,就会自动创建一个新的事件循环。而且在main中也不需要通过事件循环去掉用被包装的协程函数,只需要向普通函数那样调用即可 ,只不过使用了await关键字而已。