2016-08-03 44 views
0

如果我旋轉了一個ThreadPoolExecutor(max_workers=0)它可以與Python3.4和Python2.7一起使用,但會引發Python3.5和Python3.6的錯誤。我試圖創建一個ThreadPoolExecutor,我想確保沒有任何任務被添加到線程池中。目前,我從ThreadPoolExecutor創建了一個子類,並在重載的submit方法中產生了異常。有一個更好的方法嗎?concurrent.futures.ThreadPoolExecutor max_workers不能爲0

回答

0

簡單地說,在Python3.5和3.6中,出於理智的原因,max_workers參數不允許爲0。所以我的解決方案是創建一個更「模擬」的ThreadPoolExecutor版本,以記錄ThreadPool的活動,以防將某些內容添加到隊列中,然後對此進行斷言。我會在這裏分享代碼,以防有人想要將其用於他們的目的。

import threading 
from concurrent import futures 


class RecordingThreadPool(futures.Executor): 
    """A thread pool that records if used.""" 
    def __init__(self, max_workers): 
    self._tp_executor = futures.ThreadPoolExecutor(max_workers=max_workers) 
    self._lock = threading.Lock() 
    self._was_used = False 

    def submit(self, fn, *args, **kwargs): 
    with self._lock: 
     self._was_used = True 
    self._tp_executor.submit(fn, *args, **kwargs) 

    def was_used(self): 
    with self._lock: 
     return self._was_used 
相關問題