Python并发 future executor.submit超时

标签 python multithreading python-3.x concurrency

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

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/

相关文章:

django - Django 中的自定义 url 模式

python - 如何使用 Python 在 MySQL 数据库中存储 API 响应?

python - 即使未找到匹配项,Pandas itertuples 第一行也会返回 true

python - 递归地以螺旋顺序打印矩阵

java - 以原子方式更新两个 ConcurrentHashMap

java - JDBC:共享连接或使用连接池

python - 如何在电报机器人对话处理程序的对话中保存数据

python - 智能获取两个字符之间的文本

C#变量线程安全

python - 如何获取单行数据框中与 n 个最大值对应的列?