python multiprocessing on windows, if __name__ == "__main__"

Solution 1:

You do not have to call Process() from the "top level" of the module. It is perfectly fine to call Process from a class method.

The only caveat is that you can not allow Process() to be called if or when the module is imported.

Since Windows has no fork, the multiprocessing module starts a new Python process and imports the calling module. If Process() gets called upon import, then this sets off an infinite succession of new processes (or until your machine runs out of resources). This is the reason for hiding calls to Process() inside

if __name__ == "__main__"

since statements inside this if-statement will not get called upon import.

Solution 2:

__name__ is only ever equal to "__main__" if the script has been executed directly, either via python foo.py or python -m foo. This ensures that Process() will not be called if the script is imported as a module instead.