Python 为什么在concurrent.futures.Future实例中未引发TimeoutError
我是根据我们的样本做的 我已更新以下内容:Python 为什么在concurrent.futures.Future实例中未引发TimeoutError,python,python-3.x,concurrency,Python,Python 3.x,Concurrency,我是根据我们的样本做的 我已更新以下内容: data=future.result() 对此: data=future.result(超时=0.1) concurrent.futures.Future.result的文档说明: 如果呼叫未在超时秒内完成,则会引发TimeoutError。超时可以是int或float (我知道请求有一个超时,为60,但在我的实际代码中,我正在执行一个不使用urllib请求的不同操作) 如果我在调用时将其设置为“已完成”,则会引发TimeoutError,但我需要根据
data=future.result()
对此:
data=future.result(超时=0.1)
concurrent.futures.Future.result的文档说明:
如果呼叫未在超时秒内完成,则会引发TimeoutError。超时可以是int或float
(我知道请求有一个超时,为60,但在我的实际代码中,我正在执行一个不使用urllib请求的不同操作)
如果我在调用时将其设置为“已完成”
,则会引发TimeoutError
,但我需要根据将来的情况设置超时,而不是全部设置超时
更新
谢谢@jme,它只适用于一个未来,但不适用于使用以下公式的倍数。我是否需要在函数开始时yield
,以允许构建期货
dict?从文档中可以看出,submit
的调用不应该被阻止
import concurrent.futures
import time
import sys
def wait():
time.sleep(5)
return 42
with concurrent.futures.ThreadPoolExecutor(4) as executor:
waits = [wait, wait]
futures = {executor.submit(w): w for w in waits}
for future in concurrent.futures.as_completed(futures):
try:
future.result(timeout=1)
except concurrent.futures.TimeoutError:
print("Too long!")
sys.stdout.flush()
print(future.result())
异常正在主线程中引发,您只是没有看到它,因为stdout
尚未刷新。例如:
import concurrent.futures
import time
import sys
def wait():
time.sleep(5)
return 42
with concurrent.futures.ThreadPoolExecutor(4) as executor:
future = executor.submit(wait)
try:
future.result(timeout=1)
except concurrent.futures.TimeoutError:
print("Too long!")
sys.stdout.flush()
print(future.result())
运行此命令,您将在一秒钟后看到“太长!”出现,但解释器将再等待四秒钟,线程才能完成执行。然后您将看到42
——出现wait()
的结果
这是什么意思?设置超时不会终止线程,这实际上是一件好事。如果线程持有锁怎么办?如果我们突然杀死它,锁永远不会被释放。不,最好让线程自行处理它的消亡。类似地,future.cancel
的目的是阻止线程启动,而不是杀死它。问题似乎在于调用concurrent.futures.as_completed()
如果我将其替换为一个for
循环,那么一切似乎都正常:
for wait, future in [(w, executor.submit(w)) for w in waits]:
...
我将的文档误解为_completed
,其中说明:
…当期货完成时产生收益(完成或取消)
as_completed
将处理超时,但作为一个整体,而不是在未来的基础上。发布完整的解决方案会有所帮助
for wait, future in [(w, executor.submit(w)) for w in waits]:
...