python - 如何在多处理代码中重用池工作者?
问题描述
在下面的代码中,我收到有关“无法在模块main上获取属性 'f' ”的错误。我知道如何解决它:将池线和结果线都放在结果 2 的上方。
我的问题是为什么当前形式的代码不起作用。我正在处理更复杂的代码,我必须在两个不同的独立 for 循环中使用并行处理。现在,我在每个 for 循环的每次迭代中都有 pool=mp.Pool(3)。我在网上读到这很糟糕,因为在每次迭代中,我都会创建更多的池“工人”。如何将 pool = mp.Pool(3) 放在迭代之外,然后在我需要的代码的所有不同区域中使用相同的 Pool 工作程序?
作为记录,我正在使用 mac 来运行我的代码。
import numpy as np
import multiprocessing as mp
x = np.array([1,2,3,4,5,6])
pool = mp.Pool(3)
def f(x):
return x**2
result = pool.map(f,x)
def g(x):
return x + 1
result2 = pool.map(g,x)
print('result=',result,'and result2=',result2)
解决方案
当使用“fork”方法创建子进程(Mac OS 的默认值)时,进程在Pool
创建时被分叉(基本上是复制)。这意味着在您的代码中,分叉的孩子尚未执行创建,f
而是等待来自主进程的任务。
首先,您不应该直接在脚本中执行“活动”代码(除了定义函数、类、常量),而是将其移动到函数中。您的代码可能如下所示:
import numpy as np
import multiprocessing as mp
def f(x):
return x**2
def g(x):
return x + 1
def main():
x = np.array([1,2,3,4,5,6])
pool = mp.Pool(3)
result = pool.map(f,x)
result2 = pool.map(g,x)
print('result=',result,'and result2=',result2)
# Should be nearly the only "active" statement
main()
或者在你的情况下可能更好,我猜:
import numpy as np
import multiprocessing as mp
def f(x):
return x**2
def g(x):
return x + 1
def proc_f():
global x, pool
return pool.map(f,x)
def proc_g():
global x, pool
return pool.map(g,x)
def main():
global x, pool
x = np.array([1,2,3,4,5,6])
pool = mp.Pool(3)
result = proc_f()
result2 = proc_g()
print('result=',result,'and result2=',result2)
# Should be nearly the only "active" statement
main()
推荐阅读
- vue.js - 如何更改/覆盖 vuetify 中开关标签的默认颜色?
- input - 使用拖放功能填充输入框值
- java - MD5 整个节点连同校验和
- python - Django:request.POST 中的值正确但无法保存表单
- java - 使用流按偶数日期过滤日期
- asp.net-mvc - 无法获取页面的属性
- html - 如何在我的项目中正确安装 ngx-recaptcha?
- ios - 使用 Newtonsoft.Json,在 iOS 上不反序列化文化不变量?
- javascript - 是否可以通过 javascript 通过读取 json 文件而不是使用参数来更新安全组?
- php - 在循环结果中修剪最后一个单词的问题