带有上下文管理器的 ThreadPoolExecutor [英] ThreadPoolExecutor with context manager

查看: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),它会阻塞在那里,直到所有线程完成处理.请参阅 https://docs.python.org/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 https://docs.python.org/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆