首页 > 解决方案 > 尝试用 Python 理解 asyncio

问题描述

我正在尝试使用 asyncio 运行一些并发任务。目前,我得到了以下示例:

import asyncio
from time import sleep
from signal import SIGINT, SIGTERM, signal

async def f():
    print("Got in F")
    await asyncio.sleep(10)
    print("Finished Sleep in F")
    return "f"


async def g():
    print("Got in G")
    await asyncio.sleep(20)
    print("Finished Sleep in G")
    return "g"

async def count_timer():
    for i in range(20):
        print(i)
        sleep(1)

async def main():
    
    task_g = asyncio.create_task(g())
    task_f = asyncio.create_task(f())
    

    await task_g
    await task_f

    task_counter = asyncio.create_task(count_timer())

    await task_counter

    return

if __name__ == "__main__":
    import time
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.2f} seconds.")

我想做的是在调用 f 和 g 函数之后调用 counter_timer 函数,但仍然同时运行所有三个函数。

提前谢谢你,卢卡斯·德尔菲诺·诺盖拉。

标签: python-3.xconcurrencytaskpython-asyncio

解决方案


推荐阅读