【发布时间】: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