concurrent.futures.ThreadPoolExecutor max_workers 不能为 0

concurrent.futures.ThreadPoolExecutor max_workers can't be 0

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

简而言之,对于 Python3.5 和 3.6,出于合理原因,max_workers 参数不允许为 0。所以我的解决方案是制作一个更多 "mocky" 版本的 ThreadPoolExecutor ,它会记录 ThreadPool 的 activity 以防有东西被添加到队列中,然后对此进行断言。我将在此处共享代码,以防有人出于他们的目的而重复使用它。

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