✍74 asyncio随笔

一.asyncio.wait 和 asyncio.gather 的异同

https://www.jianshu.com/p/6872bf356af7

1. 异同点综述

image-20220407093517671

2. asyncio.wait 用法

  • 最常见的写法是:await asyncio.wait(task_list)
import asyncio
import arrow


def current_time():
    '''
    获取当前时间
    :return:
    '''
    cur_time = arrow.now().to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
    return cur_time


async def func(sleep_time):
    func_name_suffix = sleep_time        # 使用 sleep_time(函数 I/O 等待时长)作为函数名后缀,以区分任务对象
    print(f"[{current_time()}] 执行异步函数 {func.__name__}-{func_name_suffix}")
    await asyncio.sleep(sleep_time)
    print(f"[{current_time()}] 函数 {func.__name__}-{func_name_suffix} 执行完毕")
    return f"【[{current_time()}] 得到函数 {func.__name__}-{func_name_suffix} 执行结果】"


async def run():
    task_list = []
    for i in range(5):
        task = asyncio.create_task(async_func(i))
        task_list.append(task)

    done, pending = await asyncio.wait(task_list, timeout=None)
    for done_task in done:
        print((f"[{current_time()}] 得到执行结果 {done_task.result()}"))

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())


if __name__ == '__main__':
    main()

3. asyncio.gather 用法

  • 最常见的用法是:await asyncio.gather(*task_list)
import asyncio
import arrow


def current_time():
    '''
    获取当前时间
    :return:
    '''
    cur_time = arrow.now().to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
    return cur_time


async def func(sleep_time):
    func_name_suffix = sleep_time     # 使用 sleep_time(函数 I/O 等待时长)作为函数名后缀,以区分任务对象
    print(f"[{current_time()}] 执行异步函数 {func.__name__}-{func_name_suffix}")
    await asyncio.sleep(sleep_time)
    print(f"[{current_time()}] 函数 {func.__name__}-{func_name_suffix} 执行完毕")
    return f"【[{current_time()}] 得到函数 {func.__name__}-{func_name_suffix} 执行结果】"


async def run():
    task_list = []
    for i in range(5):
        task = asyncio.create_task(func(i))
        task_list.append(task)
    results = await asyncio.gather(*task_list)
    for result in results:
        print((f"[{current_time()}] 得到执行结果 {result}"))


def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())


if __name__ == '__main__':
    main()

2022.04.14 (create_task 使用)

今天晚上和同时讨论研究 事件循环的 create_task 可以在哪里运行

讨论的似懂非懂的,可能我还在做另一件事哈哈, 不过好在实验室成功的

1.结论

loop = asyncio.get_event_loop()
loop.create_task(main())  # 可以在协程内外使用

asyncio.create_task(func())  # 只能在协程内部使用
  • asyncio.create_task 源码 :

image-20220414205453879

在该方法内只有 get_running_loop() 方法,但在此之前没有 get_event_loop() 生成事件循环

所以要么传一个 loop 进去(修改源码试了试可以),要么在协程内部使用

posted @ 2022-11-10 15:22  给你骨质唱疏松  阅读(32)  评论(0编辑  收藏  举报