• 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)
  • 相关阅读:
    PL/SQL注册码
    分页sql
    js获取url值
    C语言中的bool类型 stdbool.h
    语音朗读小程序
    50. Pow(x, n)
    二维数组旋转
    用一位数组代替二维数组作为形参使用
    单链表排序——交换数据成员
    C++重载输入流、输出流运算符
  • 原文地址:https://www.cnblogs.com/RainBol/p/13612932.html
Copyright © 2020-2023  润新知