我想使用多个线程和一个线程超时。我已经使用了以下代码:
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)。它展示了如何使用映射方法来定义超时,而不是使用提交。
您知道用executor.submit方法定义超时的方法吗?
编辑:这个例子非常简单。在我的实际案例中,我有一个15000+项的列表。executor.submit()在30-60秒内运行的每个动作。但有些项目的行动在5分钟以上,我希望与这些项目的经验。
编辑2:我想在超时之后停止线程。但我不想使用Thread对象。所以这个帖子(Is there any way to kill a Thread in Python?)不能解决我的问题。我只想使用concurrent.futures模块。
发布于 2017-08-10 15:57:39
如果你真的想用超时异步执行,你可以把你的未来打包到另一个未来,所以最后一个可以等待主要的未来,整个事情将是非阻塞的。如下所示:
executor.submit(lambda: executor.submit(func, arg).result(timeout=50))
但这是相当草率和无效的。
https://stackoverflow.com/questions/32690385
复制相似问题