将只读配置共享给多个进程的正确方法是什么?

What is the right way to share a read only configuration to multiple processes?

我有一个 python 应用程序,它将为给定输入集合的每个元素创建一个进程。输入是大约 8 个元素的集合。并且应用程序读取一个主题以周期性地获取 8 个元素。

对于输入的每个元素,我创建一个新进程并将输入传递给一个函数。

该函数在本质上是 CPU 绑定的,它执行数值运算。

我的应用程序有一个配置对象,它是一个字典。我在加载主进程时在配置中加载数据,然后创建一个包含 8 个工作子池的池。

在每个进程中传递配置对象的正确机制是什么?我不想增加进程的内存占用。

举个例子:

# cpu intensive operation
def cpu_bound(input):
    ...  # complex cpu bound op
    # I want to use config here

    return output


def get_config():
    # create configuration object
    config = {
        "version": 1,
        "disable_existing_loggers": False,
        "loggers": {
            "": {
                "level": "INFO"
            }, 
            "another.module": {
                "level": "DEBUG"
            }
        }
    }


def pool_handler(inputs):
    p = Pool(8)  # 8 core machine
    results = p.map(cpu_bound, inputs)
    return results


if __name__ == "__main__":

    config = get_config()
    # get inputs from a topic
    inputs = get_inputs()
    results = pool_handler(inputs)

问题 在每个进程中使用配置的推荐方法是什么?该配置本质上是只读的,因为我只需要在应用程序启动时加载它一次。有多种方法,但对于这种情况,推荐的方法是什么?

multiprocessing.Pool 中共享静态信息的正确方法是使用 initializer 函数通过其 initargs.

进行设置

以上两个变量实际上作为 Process 构造函数参数传递给 Pool 工人,因此遵循 multiprocessing programming guidelines.

的建议

Explicitly pass resources to child processes

On Unix using the fork start method, a child process can make use of a shared resource created in a parent process using a global resource. However, it is better to pass the object as an argument to the constructor for the child process.

variable = None


def initializer(*initargs):
    """The initializer function is executed on each worker process
    once they start.

    """
    global variable

    variable = initargs


def function(*args):
    """The function is executed on each parameter of `map`."""
    print(variable)


with multiprocessing.Pool(initializer=initializer, initargs=[1, 2, 3]) as pool:
    pool.map(function, (1, 2, 3))