python - 使用多重处理以自己的方法映射数组的每个元素

标签 python multithreading flask multiprocessing

我有一个称为“规则”的类对象数组。

self.rules看起来像这样

[<creative_task.rules.rules.Rule object at 0x7fde7a33f518>, <creative_task.rules.rules.Rule object at 0x7fde7a33f830>, <creative_task.rules.rules.Rule object at 0x7fde7a33f888>, <creative_task.rules.rules.Rule object at 0x7fde7a33f8e0>]

此Rule类具有方法self.check,用于验证存储在其中的数据。

有很多规则需要验证:相对于数据库中的值,请求的值是MORE,LESS,EQUALS,BETWEEN,POSITIVE,NEGATIVE。
关于self.check函数调用的每个此类规则都会调用Clickhouse数据库以进行自我验证。

基本上,当我需要验证规则数组时,我调用check_all函数来验证所有这样的规则
rules = [在self.rules中对r进行r.check( Assets ,上下文)]
:
    def check_all(self, asset: dict, context: dict = None) -> RuleGroupResult:
        context = {} if context is None else context
        return RuleGroupResult(
            identifier=self.identifier,
            rules=[r.check(asset, context) for r in self.rules],
            groups=[g.check(asset, context) for g in self.groups],
            logical_operator=self.logical_operator,
        )


这些规则互不依赖。

现在,我想使这种验证成为一个并行过程。因此,我需要为数组中的每个Rule调用Rule.check方法,但是此调用应同时发生

最佳答案

可以使用Pool.mapoperator.methodcaller相对容易地完成此操作,因为您的参数都相同,并且该方法在每个对象上具有相同的名称:

import multiprocessing as mp  # Top of file
from operator import methodcaller

def check_all(self, asset: dict, context: dict = None) -> RuleGroupResult:
    context = {} if context is None else context
    with mp.Pool() as pool:  # Create pool
        return RuleGroupResult(
            identifier=self.identifier,
            rules=pool.map(methodcaller('check', asset, context), self.rules),  # Map in parallel
            groups=pool.map(methodcaller('check', asset, context), self.groups),
            logical_operator=self.logical_operator,
        )

关于python - 使用多重处理以自己的方法映射数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266270/

相关文章:

c# - 为单个任务创建多个线程

networking - 具有多个暴露端口的 Docker

flask - psycopg2 带 flask ,何时关闭连接

python - 'str' 对象不可调用 Django Rest Framework

python - 使用 openpyxl 排序和自动过滤 Excel

Python TastyPie - 自定义管理器方法作为过滤器?

python - 如何从字典列表中实例化不同类的对象?

java - 使用 java 线程间在控制台中进行文件传输

android - 运行一段时间后,SurfaceView破坏Surface

python - Flask 应用程序仅对本地主机可见