Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame^] | 1 | import sys |
| 2 | import threading |
| 3 | |
| 4 | __all__ = ['Popen', 'get_spawning_popen', 'set_spawning_popen', |
| 5 | 'assert_spawning'] |
| 6 | |
| 7 | # |
| 8 | # Check that the current thread is spawning a child process |
| 9 | # |
| 10 | |
| 11 | _tls = threading.local() |
| 12 | |
| 13 | def get_spawning_popen(): |
| 14 | return getattr(_tls, 'spawning_popen', None) |
| 15 | |
| 16 | def set_spawning_popen(popen): |
| 17 | _tls.spawning_popen = popen |
| 18 | |
| 19 | def assert_spawning(obj): |
| 20 | if get_spawning_popen() is None: |
| 21 | raise RuntimeError( |
| 22 | '%s objects should only be shared between processes' |
| 23 | ' through inheritance' % type(obj).__name__ |
| 24 | ) |
| 25 | |
| 26 | # |
| 27 | # |
| 28 | # |
| 29 | |
| 30 | _Popen = None |
| 31 | |
| 32 | def Popen(process_obj): |
| 33 | if _Popen is None: |
| 34 | set_start_method() |
| 35 | return _Popen(process_obj) |
| 36 | |
| 37 | def get_start_method(): |
| 38 | if _Popen is None: |
| 39 | set_start_method() |
| 40 | return _Popen.method |
| 41 | |
| 42 | def set_start_method(meth=None, *, start_helpers=True): |
| 43 | global _Popen |
| 44 | try: |
| 45 | modname = _method_to_module[meth] |
| 46 | __import__(modname) |
| 47 | except (KeyError, ImportError): |
| 48 | raise ValueError('could not use start method %r' % meth) |
| 49 | module = sys.modules[modname] |
| 50 | if start_helpers: |
| 51 | module.Popen.ensure_helpers_running() |
| 52 | _Popen = module.Popen |
| 53 | |
| 54 | |
| 55 | if sys.platform == 'win32': |
| 56 | |
| 57 | _method_to_module = { |
| 58 | None: 'multiprocessing.popen_spawn_win32', |
| 59 | 'spawn': 'multiprocessing.popen_spawn_win32', |
| 60 | } |
| 61 | |
| 62 | def get_all_start_methods(): |
| 63 | return ['spawn'] |
| 64 | |
| 65 | else: |
| 66 | _method_to_module = { |
| 67 | None: 'multiprocessing.popen_fork', |
| 68 | 'fork': 'multiprocessing.popen_fork', |
| 69 | 'spawn': 'multiprocessing.popen_spawn_posix', |
| 70 | 'forkserver': 'multiprocessing.popen_forkserver', |
| 71 | } |
| 72 | |
| 73 | def get_all_start_methods(): |
| 74 | from . import reduction |
| 75 | if reduction.HAVE_SEND_HANDLE: |
| 76 | return ['fork', 'spawn', 'forkserver'] |
| 77 | else: |
| 78 | return ['fork', 'spawn'] |