zoukankan      html  css  js  c++  java
  • asyncio async await笔记

    协程

    import asyncio
    from time import time
    
    
    async def func1():
        print('start')
        await asyncio.sleep(1)  # await关键字,后面跟一个io操作,或者一个可能会发生阻塞的方法,不然就没什么用,而且await就必须写在async里面
        print('end')
    
    
    async def func2():
        print('start')
        await asyncio.sleep(2)
        print('end')
    
    
    async def func3():
        print('start')
        await asyncio.sleep(3)
        print('end')
    
    
    # 同步执行协程操作
    loop1 = asyncio.get_event_loop()
    loop1.run_until_complete(func1())
    
    # 异步执行协程操作
    loop2 = asyncio.get_event_loop()
    this_time = time()
    loop2.run_until_complete(asyncio.wait(
        [func1(), func2(), func3()]
    ))
    end_time = time() - this_time
    print(end_time)  # 3.00   可以看到异步可以同时间完成

    获取返回值

    import asyncio
    
    async def hello():
        print("123")
        await asyncio.sleep(1)
        print("321")
        return 'done'
    
    loop = asyncio.get_event_loop()
    task = loop.create_task(hello())
    loop.run_until_complete(task)
    ret = task.result()
    print(ret)

    获取多个返回值

    import asyncio
    
    
    async def hello(i):
        print("123")
        await asyncio.sleep(1)
        print("321")
        return i
    
    
    loop = asyncio.get_event_loop()
    task1 = loop.create_task(hello(1))
    task2 = loop.create_task(hello(2))
    task_list = [task1, task2]
    loop.run_until_complete(asyncio.wait(task_list))
    for i in task_list:
        res = i.result()
        print(res)
  • 相关阅读:
    php上传文件大小修改
    flex布局
    restful
    mysql之windows忘记密码
    mysql常用命令
    比较级浅析1
    一般副词的位子
    still讲解
    英语学习法
    as的如下用法
  • 原文地址:https://www.cnblogs.com/RainBol/p/13612932.html
Copyright © 2011-2022 走看看