concurrent.futures.ThreadPoolExecutor max_workers不能为0

时间:2016-08-03 14:41:36

标签: python python-3.x concurrent.futures

如果我启动ThreadPoolExecutor(max_workers=0)它可以使用Python3.4和Python2.7,但会引发Python3.5和Python3.6的错误。我正在尝试创建一个ThreadPoolExecutor,我想确保没有任务添加到线程池中。目前,我从ThreadPoolExecutor创建了一个子类,并在重载的submit方法中引发了异常。有更好的方法吗?

1 个答案:

答案 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