blob: b0c80d5d87c863c2b04c9d6cae496f684fae144f [file] [log] [blame]
Richard Oudkerk84ed9a62013-08-14 15:35:41 +01001import sys
2import 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
13def get_spawning_popen():
14 return getattr(_tls, 'spawning_popen', None)
15
16def set_spawning_popen(popen):
17 _tls.spawning_popen = popen
18
19def 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
32def Popen(process_obj):
33 if _Popen is None:
34 set_start_method()
35 return _Popen(process_obj)
36
37def get_start_method():
38 if _Popen is None:
39 set_start_method()
40 return _Popen.method
41
42def 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
55if 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
65else:
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']