Python 3.4+multiprocessingfunction
multiprocessing.get_context()
start methods
Returns a context object with the same names as the module (Process, Queue, Pool, Lock…) but bound to the given start method.
Syntax
ctx = multiprocessing.get_context(method=None) # 'spawn' | 'fork' | 'forkserver'
This is the best way to pick spawn, fork or forkserver: unlike set_start_method() it leaves global state alone, so it is safe in libraries and can be called any number of times. The default depends on the OS and version: Windows uses spawn, macOS spawn since 3.8, Linux fork up to 3.13 and forkserver since 3.14. An explicit ctx = get_context('spawn') makes behaviour identical on every OS and avoids the DeprecationWarning that fork from a process with live threads raises since 3.12. Do not mix objects from different contexts: a Queue from one and a Process from another may fail. An unknown name raises ValueError.
Examples
import multiprocessing as mp
def square(x):
return x * x
if __name__ == '__main__':
ctx = mp.get_context('spawn')
print(ctx.get_start_method()) # → spawn
with ctx.Pool(2) as pool:
print(pool.map(square, [1, 2, 3])) # → [1, 4, 9]
import multiprocessing as mp
if __name__ == '__main__':
try:
mp.get_context('thread')
except ValueError as e:
print(e) # → cannot find context for 'thread'
print(mp.get_start_method(allow_none=True)) # → None — глобальное умолчание не тронуто
See also
Open in the full glossarydocs.python.orgReport an inaccuracy