为什么为什么巧不巧并发.futures.ThreadPoolExecutor()。submit返回? [英] Why doesn't concurrent.futures.ThreadPoolExecutor().submit return immediately?

查看:154
本文介绍了为什么为什么巧不巧并发.futures.ThreadPoolExecutor()。submit返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中:

import concurrent.futures
import time

def pafter(t):
    time.sleep(t)
    print('Hi')

with concurrent.futures.ThreadPoolExecutor(5) as e:
    e.submit(pafter, 2)

print('With returned')

我希望看到:

With returned
Hi

但我看到:

Hi
With returned

为什么不提交立即返回?我该怎么做才能做到这一点?

Why doesn't submit return immediately? What do I change to make it do so?

推荐答案

和语句等效于调用 executor.shutdown()记录如下


shutdown(wait = True)

shutdown(wait=True)

向执行人发送信号,告知其应在当前未完成的期货交易完成后释放其正在使用的任何资源执行。关闭后对Executor.submit()和Executor.map()的调用将引发RuntimeError。

Signal the executor that it should free any resources that it is using when the currently pending futures are done executing. Calls to Executor.submit() and Executor.map() made after shutdown will raise RuntimeError.

如果wait为True,则该方法将在所有待处理的期货都为true之前不返回。完成执行,与执行者相关的资源已释放。如果wait为False,则此方法将立即返回,并且当所有未决的期货执行完毕时,与执行程序关联的资源将被释放。无论wait的价值如何,整个Python程序都将在所有未完成的期货执行完毕后才会退出。

If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing.

如果与with一起使用,可以避免显式调用此方法。语句,它将关闭Executor(等待,就像在Executor.shutdown()被设置为True的情况下被调用一样)

解释您所看到的行为; submit()调用确实会立即返回,但是 with 语句将阻塞,直到完成所有提交的工作。要更改它,您不需要使用 with 语句,而是显式调用 shutdown(wait = False)

The bold sections explain the behavior you're seeing; the submit() call does return immediately, but the with statement will block until all submitted work is done. To change it, you need to not use the with statement, and instead explicitly call shutdown(wait=False).

这篇关于为什么为什么巧不巧并发.futures.ThreadPoolExecutor()。submit返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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