Sam*_*zon 5 python concurrency multithreading python-3.x
我想使用多个线程并按线程超时。我已经使用以下代码:
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)
Run Code Online (Sandbox Code Playgroud)
我已经看过这篇文章如何使用并发。未来超时?但我不需要使用结果方法
Python 文档对我没有帮助(https://docs.python.org/3/library/concurrent.futures.html)。它展示了如何使用map方法而不是submit定义超时。
您知道如何使用executor.submit方法定义超时吗?
编辑:这个例子非常简单。在我的真实案例中,我有一个包含 15000 多个项目的列表。每个操作由executor.submit()在 30 - 60 秒内运行。但有些项目的作用时间超过 5 分钟,我希望 Tiemout 除外这些项目。
编辑 2:我想在超时后停止线程。但我不想使用 Thread 对象。所以这篇文章(Is有什么方法可以杀死Python中的线程吗?)并不能解决我的问题。我只想使用并发.futures模块。
如果你真的想在超时的情况下异步执行,你可以将你的 future 打包到另一个 future 中,这样最后一个可以等待主要的 future,整个事情将是非阻塞的。像这样:
executor.submit(lambda: executor.submit(func, arg).result(timeout=50))
但这是相当草率且无效的。