2016-08-03 19 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 
相关问题