Skip to content

Latest commit

 

History

History
88 lines (58 loc) · 2.01 KB

25.协程-异步编程基本模板.md

File metadata and controls

88 lines (58 loc) · 2.01 KB

异步编程基本模板

一.实现步骤

1.构建一个入口函数

通过async定义,并且要在main函数里面await一个或者是多个协程,同前面一样,我可以通过gather或者是wait进行组合,对于有返回值的协程函数,一般就在main里面进行结果的获取。

async def main():
  result =  asyncio.gether(coro1(),coro2())

2.启动主函数

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关键字而已。