Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5046e97

Browse files
committed
Make __mp_main__ an alias for __main__ in all processes to simplify
pickling of classes defined in main module.
1 parent c3c6fe5 commit 5046e97

2 files changed

Lines changed: 13 additions & 16 deletions

File tree

Lib/multiprocessing/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@
3939
from multiprocessing.process import Process, current_process, active_children
4040
from multiprocessing.util import SUBDEBUG, SUBWARNING
4141

42+
#
43+
# Alias for main module -- will be reset by bootstrapping child processes
44+
#
45+
46+
if '__main__' in sys.modules:
47+
sys.modules['__mp_main__'] = sys.modules['__main__']
48+
4249
#
4350
# Exceptions
4451
#

Lib/multiprocessing/forking.py

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -441,27 +441,17 @@ def prepare(data):
441441
dirs = [os.path.dirname(main_path)]
442442

443443
assert main_name not in sys.modules, main_name
444+
sys.modules.pop('__mp_main__', None)
444445
file, path_name, etc = imp.find_module(main_name, dirs)
445446
try:
446-
# We would like to do "imp.load_module('__main__', ...)"
447-
# here. However, that would cause 'if __name__ ==
448-
# "__main__"' clauses to be executed.
447+
# We should not do 'imp.load_module("__main__", ...)'
448+
# since that would execute 'if __name__ == "__main__"'
449+
# clauses, potentially causing a psuedo fork bomb.
449450
main_module = imp.load_module(
450-
'__parents_main__', file, path_name, etc
451+
'__mp_main__', file, path_name, etc
451452
)
452453
finally:
453454
if file:
454455
file.close()
455456

456-
sys.modules['__main__'] = main_module
457-
main_module.__name__ = '__main__'
458-
459-
# Try to make the potentially picklable objects in
460-
# sys.modules['__main__'] realize they are in the main
461-
# module -- somewhat ugly.
462-
for obj in list(main_module.__dict__.values()):
463-
try:
464-
if obj.__module__ == '__parents_main__':
465-
obj.__module__ = '__main__'
466-
except Exception:
467-
pass
457+
sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module

0 commit comments

Comments
 (0)