我想在Python模块中使用multiprocessing
(在Windows上)。我一直在阅读在调用if __name__ == '__main__':
工具之前所需的multiprocessing
语句背后的原因,以“保护程序的入口点”。但是,如果我要在模块中使用multiprocessing
并将其作为更大包的一部分导入,__name__
变量将始终是模块的名称,不是吗?
如何在导入的子模块中使用multiprocessing
并同时“保护入口点”?
以下是我正在尝试运行的代码的相关部分:
import multiprocessing
def _redistribute_pumping(S1, E1, S2, E2, P2):
#variable for redistributed pumping
P1 = multiprocessing.Array('d', np.zeros((len(S1),)))
#setup a list of processes
processes = [multiprocessing.Process(target=_inner_distribution,
args=(S1[idx], E1[idx], S2, E2, P2, idx, range(len(S2)), P1)
) for idx in range(min_idx, max_idx + 1)]
#run the processes
for p in processes:
p.start()
#exit the completed processes
for p in processes:
p.join()
print P1
我收到此错误:
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.