python - 使用在另一个函数中定义的全局变量(一个函数)并使用局部变量进行多处理
问题描述
我对此设置进行了一些测试,结果出乎意料地快速解决了我的问题:
我想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
而不是许多参数似乎更具可读性......
解决方案
您现在拥有的东西看起来不错,但对于以后的更改可能很脆弱。
我可能会使用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()
推荐阅读
- postgresql - Pyspark Dataframe Insert 覆盖并具有多个分区
- ruby - Cucumber 如何解析配置文件中的环境变量?
- c# - 检查列表顺序是错还是对,如何使代码清晰
- isabelle - 规则 conjI 拆分所有项
- python - 突出显示超过一周的日期单元格!!!Dash
- angular - 路由器链接活动显示上一个选项卡在浏览器背面活动
- json - 使用 postgres 在 Django 中高效存储 Json
- r - 如何从R中的列表中为多个对象(但不是全部)中的特定列提供格式(在这种情况下为“毫秒”)
- c# - 如何共享扩展的自定义 SQL 代码分析规则 dll
- c++ - 从协程产生值时出错“错误:成员引用基类型'void'不是结构或联合”