ThreadPoolExecutor 内部机制

2 投票
1 回答
1185 浏览
提问于 2025-04-17 12:57

我正在使用 concurrent.futures 里的 ThreadPoolExecutor 类来对一个网络服务进行压力测试。

根据我的理解,max_workers 这个参数是告诉执行器,线程池里最多可以有多少个线程。不过,我想知道,这个数字是否一定会被完全使用?或者说,实际使用的线程数量可能会因为一些硬件限制而少于这个数字吗?

如果是这样的话,有没有办法知道实际会创建多少个工作线程呢?

1 个回答

2

根据文档的内容

    Args:
        max_workers: The maximum number of threads that can be used to
            execute the given calls.

从代码来看,_adjust_thread_count() 这个函数似乎是根据需要来创建新线程的,而且这个数量是受到 max_workers 的限制的。

    if len(self._threads) < self._max_workers:
        t = threading.Thread(target=_worker,
                             args=(weakref.ref(self, weakref_cb),
                                   self._work_queue))

另外,len(self._threads) 这个部分似乎是用来表示实际创建的线程数量。

撰写回答