簡體   English   中英

Python:等待所有`concurrent.futures.ThreadPoolExecutor`的期貨

[英]Python: Wait on all of `concurrent.futures.ThreadPoolExecutor`'s futures

我已經給了concurrent.futures.ThreadPoolExecutor一堆任務,我想等到它們都完成后再繼續流程。 我怎樣才能做到這一點,而不必保存所有期貨並wait它們? (我想對執行者采取行動。)

只需調用Executor.shutdown

shutdown(wait=True)

當當前掛起的期貨完成執行時,向執行器發出信號,它應該釋放它正在使用的任何資源。 關閉后對Executor.submit()Executor.map()調用將引發RuntimeError

如果 wait 為True則此方法將不會返回,直到所有掛起的期貨都執行完畢並且與執行程序關聯的資源已被釋放。

但是,如果您在列表中跟蹤您的期貨,那么您可以避免使用futures.wait()函數關閉執行程序以供將來使用:

concurrent.futures.wait(fs, timeout=None, return_when=ALL_COMPLETED)

等待fs給出的Future實例(可能由不同的Executor實例創建)完成。 返回一個命名的 2 元組集合。 第一個名為 done 的集合包含在等待完成之前完成(完成或被取消)的期貨。 第二組名為 not_done,包含未完成的期貨。

請注意,如果您不提供timeout它會等到所有期貨都完成。

您也可以使用futures.as_completed()代替,但是您必須對其進行迭代。

巴庫留的回答是正確的。 只是為了擴展一點。 眾所周知,上下文管理器具有__enter____exit__方法。 這是class ExecutorThreadPoolExecutor 的基類)的定義方式

class Executor(object):

    # other methods

    def shutdown(self, wait=True):
        """Clean-up the resources associated with the Executor.

        It is safe to call this method several times. Otherwise, no other
        methods can be called after this one.

        Args:
            wait: If True then shutdown will not return until all running
                futures have finished executing and the resources used by the
                executor have been reclaimed.
        """
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.shutdown(wait=True)
        return False

而真正定義shutdown方法的是ThreadPoolExecutor

class ThreadPoolExecutor(_base.Executor):
    def shutdown(self, wait=True):
        with self._shutdown_lock:
            self._shutdown = True
            self._work_queue.put(None)
        if wait:
            for t in self._threads:
                t.join()

如前所述,可以使用Executor.shutdown(wait=True) ,但還要注意文檔中的以下注釋:

如果您使用with語句,您可以避免顯式調用此方法,這將關閉Executor (等待就像Executor.shutdown()是在wait設置為True情況下調用的):

 import shutil with ThreadPoolExecutor(max_workers=4) as e: e.submit(shutil.copy, 'src1.txt', 'dest1.txt') e.submit(shutil.copy, 'src2.txt', 'dest2.txt') e.submit(shutil.copy, 'src3.txt', 'dest3.txt') e.submit(shutil.copy, 'src4.txt', 'dest4.txt')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM