首页 > 解决方案 > 使用在另一个函数中定义的全局变量(一个函数)并使用局部变量进行多处理

问题描述

我对此设置进行了一些测试,结果出乎意料地快速解决了我的问题:

我想multiprocessing.Pool.map()从函数内部调用 a main(设置参数)。但是,将本地定义的函数作为参数之一对我来说更简单。由于后者不能被腌制,我尝试了将其声明为 global的最懒惰的解决方案。我应该期待一些奇怪的结果吗?你会建议不同的策略吗?

这是一个示例(虚拟)代码:

#!/usr/bin/env python3

import random
import multiprocessing as mp


def processfunc(arg_and_func):
    arg, func = arg_and_func
    return "%7.4f:%s" %(func(arg), arg)


def main(*args):
    # the content of var depends of main:
    var = random.random()

    # Now I need to pass a func that uses `var`
    global thisfunc
    def thisfunc(x):
        return x+var

    # Test regular use
    for x in range(-5,0):
        print(processfunc((x, thisfunc)))

    # Test parallel runs.
    with mp.Pool(2) as pool:
        for r in pool.imap_unordered(processfunc, [(x, thisfunc) for x in range(20)]):
            print(r)

if __name__=='__main__':
    main()

PS:我知道我可以thisfunc在模块级别定义,并通过 传递var参数processfunc,但是由于我processfunc在现实生活中的实际已经接受了很多参数,因此传递单个对象thisfunc而不是许多参数似乎更具可读性......

标签: pythonmultiprocessingglobal-variablespickle

解决方案


您现在拥有的东西看起来不错,但对于以后的更改可能很脆弱。

我可能会使用partial它来简化对var全局定义函数的显式传递。

import random
import multiprocessing as mp
from functools import partial

def processfunc(arg_and_func):
    arg, func = arg_and_func
    return "%7.4f:%s" %(func(arg), arg)

def thisfunc(var, x):
    return x + var

def main(*args):
    # the content of var depends of main:
    var = random.random()
    f = partial(thisfunc, var)

    # Test regular use
    for x in range(-5,0):
        print(processfunc((x, thisfunc)))

    # Test parallel runs.
    with mp.Pool(2) as pool:
        for r in pool.imap_unordered(processfunc, [(x, f) for x in range(20)]):
            print(r)

if __name__=='__main__':
    main()

推荐阅读