简而言之,需要在p=Process()前加上 if __name__ == ‘__main__’: p = Process(...
Safe importing of main module
Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).
For example, under Windows running the following module would fail with a RuntimeError:
from multiprocessing import Process
def foo(): print 'hello'
p = Process(target=foo) p.start()
Instead one should protect the “entry point” of the program by using if __name__ == '__main__': as follows:
from multiprocessing import Process, freeze_support
def foo(): print 'hello'
if __name__ == '__main__': freeze_support() p = Process(target=foo) p.start()
(The freeze_support() line can be omitted if the program will be run normally instead of frozen.)
This allows the newly spawned Python interpreter to safely import the module and then run the module’s foo() function.