python - 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")
执行(即在所有线程都执行完之后)。然而,不是吗?我错过了什么?
解决方案
我认为这与 Pycharm 控制台缓冲输出的方式有关(您在屏幕截图中显示)
我在 pycharm 中运行了几次,它有时会起作用,而其他时候则不起作用。但是,当您在终端中运行它(或告诉 pycharm“模拟终端输出”)时,我再也看不到它了
推荐阅读
- amazon-web-services - SignalR 在 AWS EB 后面部署时无法连接
- javascript - 使用 three.js 导入 3d 模型
- wordpress - 在多个商店中复制 Woocommerce 产品
- ruby-on-rails-5 - Rails:用于 `invoice.payment_action_required` 和 `invoice.payment_failed` 的条纹 webhook
- react-native - 如何在本机反应中删除弯曲之间的空间?(flexWrap)
- aws-lambda - 使用 Java 创建 URL 签名 - Cloudfront - InvalidKey - Unknown Key
- python - Python模块'scm'没有属性'Open'
- regex - 使用 Dockerhub Regex 进行自动构建
- json - 解析包含 json 字符串的 json
- kubernetes - Kubernetes 的 pod 状态为 CrashLoopBackOff 但没有显示日志