简体   繁体   English

Python ThreadPoolExecutor:未按预期工作?

[英]Python ThreadPoolExecutor: Not working as expected?

According to realpython :根据realpython

The end of the with block causes the ThreadPoolExecutor to do a .join() on each of the threads in the pool. with 块的结尾导致 ThreadPoolExecutor 对池中的每个线程执行 .join() 。 It is strongly recommended that you use ThreadPoolExecutor as a context manager when you can so that you never forget to .join() the threads.强烈建议您尽可能使用 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")

In the given code snippet, I was expecting that the last line - print("all done") to be executed at the end (ie after all the threads are done executing).在给定的代码片段中,我期望最后一行 - print("all done")在最后执行(即在所有线程执行完毕后)。 However, it is not?然而,不是吗? what am I missing?我错过了什么?

I think it has something to do with the way the Pycharm console buffers output (that you showed in your screenshot)我认为这与 Pycharm 控制台缓冲输出的方式有关(您在屏幕截图中显示)

I run it several times in pycharm and it worked sometimes, while not working other times.我在 pycharm 中多次运行它,它有时工作,而其他时候不工作。 However, when you run it in the terminal (or tell pycharm to "emulate terminal output") I don't see it anymore但是,当您在终端中运行它(或告诉 pycharm“模拟终端输出”)时,我再也看不到它了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM