带有上下文管理器的 ThreadPoolExecutor

编程入门 行业动态 更新时间:2024-10-24 03:21:49
本文介绍了带有上下文管理器的 ThreadPoolExecutor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不明白为什么这段代码的行为方式不同.在第一种情况下,代码将打印elo",19 秒后我们将看到3".

I don't understand why this code is behaving in different way. In the first case, the code will print 'elo' and after 19 seconds we will see '3'.

在其他情况下,我们将首先等待 19 秒,然后我们将看到 'elo'.

In other case we will be first wait 19 seconds, and after that we will see 'elo'.

你能解释一下吗?

from concurrent.futures import ThreadPoolExecutor def wait_on_future(): f = 3 import time time.sleep(19) print(f) executor = ThreadPoolExecutor(max_workers=2) executor.submit(wait_on_future) print("elo")

对比

from concurrent.futures import ThreadPoolExecutor def wait_on_future(): f = 3 import time time.sleep(19) print(f) with ThreadPoolExecutor(max_workers=2) as executor: executor.submit(wait_on_future) print("elo")

推荐答案

您的第一个程序没有明确关闭池.您使用 executor.submit() 提交您的任务,这是一个非阻塞调用.您的主程序会立即处理打印语句并挂在那里,直到所有线程在 19 秒后完成.

Your first program does not explicitly close the pool. You submit your task with executor.submit(), which is a non-blocking call. Your main program processes to print statement immediately and just hangs there until all threads have finished after 19 seconds.

你的第二个程序使用 with 语句,在这个上下文中它是阻塞的.with ThreadPoolExecutor() 有一个隐含的 shutdown(wait=True),它会阻塞在那里,直到所有线程完成处理.请参阅 docs.python/3/library/concurrent.futures.html

Your second program uses with statement, which in this context is blocking. with ThreadPoolExecutor() has an implicit shutdown(wait=True), and it blocks there until all threads have completed processing. See docs.python/3/library/concurrent.futures.html

这使您的程序 1 在功能上与您的程序 2 相同:

This makes your program1 identical in functionality as is your program 2:

executor = ThreadPoolExecutor(max_workers=2) executor.submit(wait_on_future) executor.shutdown(wait=True) print("elo")

希望这会有所帮助.

更多推荐

带有上下文管理器的 ThreadPoolExecutor

本文发布于:2023-11-23 10:05:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621045.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   管理器   ThreadPoolExecutor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!