In the below code, I get an error about "can't get attribute 'f' on module main". I know how to fix it: bring the pool line and the result line both to just above result 2.
My question is why the code in its current form doesn't work. I am working with more complicated code where I have to use parallel processing inside of two different separate for loops. Right now, I have in each iteration of each for loop, pool=mp.Pool(3). I read online that this is bad because in each iteration, I am creating more Pool "workers." How can I put pool = mp.Pool(3) on the outside of the iteration and then use the same Pool workers in all of the different areas of my code that I need to?
For the record, I am using a mac to run my code.
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)