【问题标题】:ThreadPoolExecutor number of threadsThreadPoolExecutor 线程数
【发布时间】:2014-03-13 17:34:30
【问题描述】:

我正在尝试使用 futures backport 包在 Python 中使用 ThreadPoolExecutor。然而,问题是所有线程都是同时执行的,因此没有发生实际的池化。更具体地说,我得到了该函数的 10 个线程,而不是 5 个线程,然后是其他线程。我使用下面的代码你发现有什么问题还是只是向后移植的实现? 谢谢!

with ThreadPoolExecutor(max_workers=5) as executor:
    futures = [executor.submit(f, X, y) for t in range(10)]
    for future in as_completed(futures):
        self.trees.append(future.result())

【问题讨论】:

  • 你确定吗?你怎么知道f并发调用数不限于max_workers
  • 是的,如果我将打印命令添加到“f”,我会使用 python 2.7 一次性收到 10 条详细消息
  • time.sleep(5) 添加到f 以查看并非所有10 个函数都同时运行。
  • @iassael 输出被缓冲,看到两条消息快速顺序打印并不意味着相应的print 同时执行。尝试使用python -u(无缓冲)执行,或者更好的是,使用任务管理器来验证启动了多少线程。

标签: python multithreading thread-safety threadpoolexecutor concurrent.futures


【解决方案1】:

在文档中它说每个工作人员通常有多个线程:

https://docs.python.org/3/library/concurrent.futures.html

在 3.5 版更改:如果 max_workers 为 None 或未给出,则默认为机器上的处理器数量,乘以 5,假设 ThreadPoolExecutor 经常用于重叠 I/O 而不是 CPU 工作和数量工人数应高于 ProcessPoolExecutor 的工人数。

可能它不会默认为 5 乘数,因为您使用的版本不是 3.5+ 或其他一些内部优化原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多