I am a physicist and I am new to Python just recently migrated from MATLAB. I need to implement multiprocessing to perform calculations for a genetic optimization algorithm.
I have managed to make multiprocessing work in single python file using information I found on-line. This is an example code I created to replicate the problem (it doesn't do anything useful).
import numpy as np
import multiprocessing as mp
def fun1((index, array)):
lst_1=[]
for ar_i in array:
lst_1.append(ar_i+index)
return np.sum(np.squeeze(lst_1))
def main(N):
arr=np.arange(1,N)
lst=[]
for elem in arr:
lst.append((elem,arr))
p = mp.Pool(8)
a=p.map(fun1, lst)
return a
if __name__ == "__main__":
ans=main(30)
If I run this from the Python console it gives me the answer. Also from the Python console I can import the function from the Python file and it also works. For example:
import example1
ans2=example1.main(20)
But if I am in another Python file (for example the main genetic algorithm file) and I import the function again and try to run it as:
import example1
ans3=example1.main(10)
I get an error message:
"RuntimeError:
Attempt to start a new process before the current process
has finished its bootstrapping phase.
This probably means that you are on Windows and you have
forgotten to use the proper idiom in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce a Windows executable."
How can I solve this problem? I searched online but I haven't been able to figure this out. Perhaps I am missing something obvious. Thank you.