首页 > 解决方案 > Python ThreadPoolExecutor:没有按预期工作?

问题描述

根据realpython

with 块的结尾导致 ThreadPoolExecutor 对池中的每个线程执行 .join() 。强烈建议您尽可能使用 ThreadPoolExecutor 作为上下文管理器,这样您就永远不会忘记 .join() 线程。

import logging
# import threading
import time
import concurrent.futures

def thread_function(name):
    logging.info("Thread %s: starting", name)
    time.sleep(2)
    logging.info("Thread %s: finishing", name)


if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        executor.map(thread_function, range(3))

    print("all done")

在给定的代码片段中,我期望最后一行 - 在最后print("all done")执行(即在所有线程都执行完之后)。然而,不是吗?我错过了什么?

标签: pythonmultithreading

解决方案


我认为这与 Pycharm 控制台缓冲输出的方式有关(您在屏幕截图中显示)

我在 pycharm 中运行了几次,它有时会起作用,而其他时候则不起作用。但是,当您在终端中运行它(或告诉 pycharm“模拟终端输出”)时,我再也看不到它了


推荐阅读