python asyncio 函数 add_done_callback 不工作

python asyncio function add_done_callback is not working

我正在使用 Set() 在我的程序中执行速率限制功能。 但是有一些奇怪的行为。

  1. task_set 中有一些不应该发生的残留物。我添加了 add_done_callback 任务完成后会从 task_set 中删除。

  2. 有时会抛出KeyError。但我不知道为什么,task_set 中的任务不应被删除超过 1 次

我尝试了不同的方法(信号量、队列...),但其中 none 按预期工作...如果有人可以分享一些关于如何在异步编程

import asyncio


def main():
    async def task(acc_id):
        print(f"acc_id {acc_id} received the task")
        await asyncio.sleep(5)
        print(f"acc_id {acc_id} finished the task")

    async def loop_tasks():
        task_set = set()

        for acc_id in range(1000000):
            # pause when reached the limit
            while len(task_set) > 10:
                await asyncio.sleep(0)

            t = event_loop.create_task(task(acc_id))
            task_set.add(t)
            t.add_done_callback(lambda _: task_set.remove(t))

    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(loop_tasks())


main()

查看程序输出异常,发现t是同一个值

documentation 的回顾表明,当调用 callback 时,Future 对象是它唯一的参数。

进行如下修改后,程序运行正常。

t.add_done_callback(lambda current_task: task_set.remove(current_task))