zoukankan      html  css  js  c++  java
  • python async await 用洗衣服的场景来说明白

    import time
    import asyncio


    def demo1():
    """普通版本 阻塞 需要9秒钟执行完毕"""
    def wash1():
    time.sleep(3)
    print("wash1 finished")

    def wash2():
    time.sleep(3)
    print("wash2 finished")

    def wash3():
    time.sleep(3)
    print("wash3 finished")

    wash1()
    wash2()
    wash3()


    def demo2():
    """添加async关键字 创建协程 但是这个版本会报错:RuntimeWarning: Enable tracemalloc to get the object allocation traceback"""
        async def wash1():
    time.sleep(3)
    print("wash1 finished")

    async def wash2():
    time.sleep(3)
    print("wash2 finished")

    async def wash3():
    time.sleep(3)
    print("wash3 finished")

    wash1()
    wash2()
    wash3()


    def demo3():
    """用async 和 await创建正确的协程 这个只需要3秒钟左右!"""
    async def wash1():
    await asyncio.sleep(3) # 返回来一个可等待的对象, await后面必须跟一个awaitable类型或者具有 __await__属性的对象!
    print("wash1 finished")

    async def wash2():
    await asyncio.sleep(3)
    print("wash2 finished")

    async def wash3():
    await asyncio.sleep(3)
    print("wash3 finished")

    # 调用需要事件循环机制
    # step1 创建一个事件循环
    loop = asyncio.get_event_loop()

    # step2 将异步函数(协程)加入事件队列
    tasks = [
    wash1(),
    wash2(),
    wash3()
    ]

    # step3 执行事件队列 直到最晚的一个事件被处理完毕后结束
    loop.run_until_complete(asyncio.wait(tasks))

    # step4 如果不再使用loop 建议养成良好的关闭的习惯
    loop.close()


  • 相关阅读:
    Web中的图标(Sprites雪碧图、Icon Font字体图标)
    那些不推荐使用的html标签
    Vim学习
    web前端性能优化建议
    开发基础
    数据库事务
    java集合详解
    java基础总结大纲(一)
    java设计模式之单例模式(饿汉)
    java设计模式之单例模式(内部静态类)
  • 原文地址:https://www.cnblogs.com/yuzhaoblog/p/13207979.html
Copyright © 2011-2022 走看看