async await(python)

简单记录一下async await在Python中的用法

以洗衣机洗衣服为例,假设有3台洗衣机,每台洗衣机都需要洗一些衣服
一种做法就是依次启动每一台洗衣机,当一台洗衣机结束任务后,开始下一台

from time import sleep, time

def laundry():

    def washer1():
        print('washer one begin:...')
        sleep(3) #启动洗衣机,开洗
        print('washer one finish.')

    def washer2():
        print('washer two begin:...')
        sleep(1)
        print('washer two finish.')

    def washer3():
        print('washer three begin:...')
        sleep(5)
        print('washer three finish.')

    washer1()
    washer2()
    washer3()

laundry()

现实生活中,我们通常可以直接启动所有洗衣机,不需要在当前洗衣机彻底结束后在启动下一台
在程序中也可以模拟相同的操作

from time import sleep, time

def laundry():
    import asyncio

    async def washer1(): # async 表示该函数是个异步函数
        print('washer one begin:...')
        await asyncio.sleep(3) # await只能在异步函数中使用,后面必须接一个awaitable类型
        print('washer one finish.')

    async def washer2():
        print('washer two begin:...')
        await asyncio.sleep(1)
        print('washer two finish.')

    async def washer3():
        print('washer three begin:...')
        await asyncio.sleep(5)
        print('washer three finish.')

    # 创建任务
    loop = asyncio.get_event_loop()

    tasks = [washer1(), washer2(), washer3()]

    loop.run_until_complete(asyncio.wait(tasks))

    loop.close()

if __name__ == '__main__':
    start = time()

    laundry()

    end = time()

    print(end - start)
washer three begin:...
washer two begin:...
washer one begin:...
washer two finish.
washer one finish.
washer three finish.
5.2022106647491455

原本9s完成的任务现在只用了5.2s

参考资料:
https://blog.csdn.net/Likianta/article/details/90123678

posted @ 2024-05-05 23:10  何太狼  阅读(12)  评论(0编辑  收藏  举报