gpt4 book ai didi

Python并发 future executor.submit超时

转载 作者:行者123 更新时间:2023-12-02 04:46:05 24 4
gpt4 key购买 nike

我想通过线程使用多个线程超时。
我已经使用以下代码:

import concurrent.futures

class Action:

def __init(self):
self.name = 'initial'

def define_name(self):
# In my real code this method is executed during 30-60 seconds
self.name = 'name'

action_list = [
Action(),
Action(),
]

with concurrent.futures.ThreadPoolExecutor(
max_workers = 20
) as executor:
for action_item in action_list:
# without timeout arg, it works !
executor.submit(action_item.define_name, timeout=1)

for action_item in action_list:
print(action_item.name)

我已经看过这篇文章 How to use concurrent.futures with timeouts?但我不需要使用结果方法

Python 文档对我没有帮助( https://docs.python.org/3/library/concurrent.futures.html )。它显示了如何使用 定义超时。 map 方法,但不是提交。

你知道用 定义超时的方法吗? executor.submit 方法 ?

编辑 : 这个例子很简单。在我的真实案例中,我有一个包含 15000 多个项目的列表。 执行的每个操作executor.submit() 在 30 - 60 秒内。但是一些项目在超过 5 分钟的时间内 Action ,我想用这些项目执行 Tiemout。

编辑 2 :我想在超时后停止线程。但我不想使用 Thread 对象。所以这篇文章( Is there any way to kill a Thread in Python?)不能解决我的问题。我只想使用 并发 future 模块。

最佳答案

如果你真的想用超时异步执行,你可以将你的 future 打包在另一个 future 中,这样最后一个就可以等待主要的 future ,整个事情将是非阻塞的。像这样:
executor.submit(lambda: executor.submit(func, arg).result(timeout=50))
但这是相当草率和无效的。

关于Python并发 future executor.submit超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com