【问题标题】:Python concurrent futures executor.submit timeoutPython并发期货executor.submit超时
【发布时间】:2015-09-21 08:17:05
【问题描述】:

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

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)。它展示了如何使用 ma​​p 方法而不是提交来定义超时。

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

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

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

【问题讨论】:

  • submit() 超时应该做什么? ThreadPoolExecutor 将提交的项目放入队列中,这意味着 submit() 并不是真正的阻塞操作。只有当队列已满且默认队列没有限制时才会发生阻塞。
  • 是的,这个例子很简单。我已经完成了更多详细信息的帖子。
  • 这不会与您的代码相加。即使有几千个项目,submit() 也应该是即时的。 submit() 只安排一个任务(稍后)执行,它不等待任务完成。这段代码中没有任何内容可以让submit() 花费 30 多秒。
  • 是的,我同意你的看法。你能想象 Action.define_name() 方法需要 30+ 秒吗?我无法发布我公司的真实代码。我发布了一个简单的用例。
  • 在这种情况下,您希望中断线程它已经在运行,而不是等待它的提交。 submit() 返回一个 Future 对象,该对象具有带有超时的 wait() 方法。你也许可以使用它。但是编写工作代码可能更优雅,以便在达到超时时自行停止。简单地杀死一个线程通常不是一个好主意。

标签: python multithreading python-3.x concurrency


【解决方案1】:

如果你真的想用超时异步执行,你可以将你的未来打包到另一个未来中,这样最后一个就可以等待主要的未来,整个事情将是非阻塞的。像这样:

executor.submit(lambda: executor.submit(func, arg).result(timeout=50))

但这很草率且无效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多