如何创建一个 Python 并发 Future,在 Future 列表完成时发出信号?

问题描述 投票:0回答:2

我有一个函数,可以向

ThreadPoolExecutor
提交多个任务,并返回每次提交创建的 Future 列表:

def submit_tasks() -> [Future]:
    futures = []

    for i in range(10):
        future = executor.submit(Task())
        futures.append(future)

    return futures

def submit() -> Future:
    futures = submit_tasks()
    
    # I would like this function to return a single Future that clients can use to check
    # whether all futures in the list have completed. How to do that?

我使用的是Python 3.8

我希望此函数返回一个 Future,客户端可以使用它来检查列表中的所有 future 是否已完成。如何做到这一点?

python python-3.x concurrency concurrent.futures
2个回答
0
投票

使用

concurrent.futures.wait
https://docs.python.org/3/library/concurrent.futures.html#module-functions

from concurrent.futures import Future, wait

...

def submit() -> Future:
    return wait(submit_tasks())

0
投票

我需要完全相同的东西并尝试了接受的答案。但它不符合要求。

所以我创建了CombinedFuture(一个辅助类),它可以:
https://gist.github.com/Klotzi111/9ab06b0380702cd5f4044c7529bdc096

© www.soinside.com 2019 - 2024. All rights reserved.