concurrent.futures.as_completed 是如何工作的?

How does concurrent.futures.as_completed work?

我正在学习 python 并发性,并且向我介绍了期货的概念。我读到 as_completed() 需要一个可迭代的期货并在完成时产生它们。

我想知道它在内部是如何工作的。它是否立即产生已完成的任务(期货)?一种天真的方法是迭代所有未来并使用 done() 检查每个未来,但这是低效的。

那么这个函数背后的魔法是什么?

谢谢!

I want to know how it works internally.

as_completed 设置回调以在 future 完成时触发,对它收到的所有 futures 这样做。 (它使用一个等同于 add_done_callback for this purpose.) When any of the futures completes, as_completed is notified by its callback being run. The callback runs in whatever thread it was that completed the future, so it only sets an event 的内部 API,它被所有回调共享,并且 as_completed 休眠。一旦被事件唤醒,as_completed 立即产生完成的未来。这就是 as_completed 确保期货在完成时产生的方式,无论发生的顺序如何。在产生之后,事件被清除并重复等待,直到所有期货完成。

Is it yielding completed tasks (futures) immediately?

是的,documented interface and the implementation