Debian Codegraph @

Doc/library/multiprocessing.rst

raw
1 :mod:`!multiprocessing` --- Process-based parallelism
2 =====================================================
3
4 .. module:: multiprocessing
5 :synopsis: Process-based parallelism.
6
7 **Source code:** :source:`Lib/multiprocessing/`
8
9 --------------
10
11 .. include:: ../includes/wasm-mobile-notavail.rst
12
13 Introduction
14 ------------
15
16 :mod:`!multiprocessing` is a package that supports spawning processes using an
17 API similar to the :mod:`threading` module. The :mod:`!multiprocessing` package
18 offers both local and remote concurrency, effectively side-stepping the
19 :term:`Global Interpreter Lock <global interpreter lock>` by using
20 subprocesses instead of threads. Due
21 to this, the :mod:`!multiprocessing` module allows the programmer to fully
22 leverage multiple processors on a given machine. It runs on both POSIX and
23 Windows.
24
25 The :mod:`!multiprocessing` module also introduces the
26 :class:`~multiprocessing.pool.Pool` object which offers a convenient means of
27 parallelizing the execution of a function across multiple input values,
28 distributing the input data across processes (data parallelism). The following
29 example demonstrates the common practice of defining such functions in a module
30 so that child processes can successfully import that module. This basic example
31 of data parallelism using :class:`~multiprocessing.pool.Pool`, ::
32
33 from multiprocessing import Pool
34
35 def f(x):
36 return x*x
37
38 if __name__ == '__main__':
39 with Pool(5) as p:
40 print(p.map(f, [1, 2, 3]))
41
42 will print to standard output ::
43
44 [1, 4, 9]
45
46 The :mod:`!multiprocessing` module also introduces APIs which do not have
47 analogs in the :mod:`threading` module, like the ability to :meth:`terminate
48 <Process.terminate>`, :meth:`interrupt <Process.interrupt>` or :meth:`kill
49 <Process.kill>` a running process.
50
51 .. seealso::
52
53 :class:`concurrent.futures.ProcessPoolExecutor` offers a higher level interface
54 to push tasks to a background process without blocking execution of the
55 calling process. Compared to using the :class:`~multiprocessing.pool.Pool`
56 interface directly, the :mod:`concurrent.futures` API more readily allows
57 the submission of work to the underlying process pool to be separated from
58 waiting for the results.
59
60
61 The :class:`Process` class
62 ^^^^^^^^^^^^^^^^^^^^^^^^^^
63
64 In :mod:`!multiprocessing`, processes are spawned by creating a :class:`Process`
65 object and then calling its :meth:`~Process.start` method. :class:`Process`
66 follows the API of :class:`threading.Thread`. A trivial example of a
67 multiprocess program is ::
68
69 from multiprocessing import Process
70
71 def f(name):
72 print('hello', name)
73
74 if __name__ == '__main__':
75 p = Process(target=f, args=('bob',))
76 p.start()
77 p.join()
78
79 To show the individual process IDs involved, here is an expanded example::
80
81 from multiprocessing import Process
82 import os
83
84 def info(title):
85 print(title)
86 print('module name:', __name__)
87 print('parent process:', os.getppid())
88 print('process id:', os.getpid())
89
90 def f(name):
91 info('function f')
92 print('hello', name)
93
94 if __name__ == '__main__':
95 info('main line')
96 p = Process(target=f, args=('bob',))
97 p.start()
98 p.join()
99
100 For an explanation of why the ``if __name__ == '__main__'`` part is
101 necessary, see :ref:`multiprocessing-programming`.
102
103 The arguments to :class:`Process` usually need to be picklable so they can be
104 passed to the child process. If you tried typing the above example directly
105 into a REPL it could lead to an :exc:`AttributeError` in the child process
106 trying to locate the *f* function in the ``__main__`` module.
107
108
109 .. _multiprocessing-start-methods:
110
111 Contexts and start methods
112 ^^^^^^^^^^^^^^^^^^^^^^^^^^
113
114 Depending on the platform, :mod:`!multiprocessing` supports three ways
115 to start a process. These *start methods* are
116
117 .. _multiprocessing-start-method-spawn:
118
119 *spawn*
120 The parent process starts a fresh Python interpreter process. The
121 child process will only inherit those resources necessary to run
122 the process object's :meth:`~Process.run` method. In particular,
123 unnecessary file descriptors and handles from the parent process
124 will not be inherited. Starting a process using this method is
125 rather slow compared to using *fork* or *forkserver*.
126
127 Available on POSIX and Windows platforms. The default on Windows and macOS.
128
129 .. _multiprocessing-start-method-fork:
130
131 *fork*
132 The parent process uses :func:`os.fork` to fork the Python
133 interpreter. The child process, when it begins, is effectively
134 identical to the parent process. All resources of the parent are
135 inherited by the child process. Note that safely forking a
136 multithreaded process is problematic.
137
138 Available on POSIX systems.
139
140 .. versionchanged:: 3.14
141 This is no longer the default start method on any platform.
142 Code that requires *fork* must explicitly specify that via
143 :func:`get_context` or :func:`set_start_method`.
144
145 .. versionchanged:: 3.12
146 If Python is able to detect that your process has multiple threads, the
147 :func:`os.fork` function that this start method calls internally will
148 raise a :exc:`DeprecationWarning`. Use a different start method.
149 See the :func:`os.fork` documentation for further explanation.
150
151 .. _multiprocessing-start-method-forkserver:
152
153 *forkserver*
154 When the program starts and selects the *forkserver* start method,
155 a server process is spawned. From then on, whenever a new process
156 is needed, the parent process connects to the server and requests
157 that it fork a new process. The fork server process is single threaded
158 unless system libraries or preloaded imports spawn threads as a
159 side-effect so it is generally safe for it to use :func:`os.fork`.
160 No unnecessary resources are inherited.
161
162 Available on POSIX platforms which support passing file descriptors over
163 Unix pipes such as Linux. The default on those.
164
165 .. versionchanged:: 3.14
166 This became the default start method on POSIX platforms.
167
168 .. versionchanged:: 3.4
169 *spawn* added on all POSIX platforms, and *forkserver* added for
170 some POSIX platforms.
171 Child processes no longer inherit all of the parents inheritable
172 handles on Windows.
173
174 .. versionchanged:: 3.8
175
176 On macOS, the *spawn* start method is now the default. The *fork* start
177 method should be considered unsafe as it can lead to crashes of the
178 subprocess as macOS system libraries may start threads. See :issue:`33725`.
179
180 .. versionchanged:: 3.14
181
182 On POSIX platforms the default start method was changed from *fork* to
183 *forkserver* to retain the performance but avoid common multithreaded
184 process incompatibilities. See :gh:`84559`.
185
186
187 On POSIX using the *spawn* or *forkserver* start methods will also
188 start a *resource tracker* process which tracks the unlinked named
189 system resources (such as named semaphores or
190 :class:`~multiprocessing.shared_memory.SharedMemory` objects) created
191 by processes of the program. When all processes
192 have exited the resource tracker unlinks any remaining tracked object.
193 Usually there should be none, but if a process was killed by a signal
194 there may be some "leaked" resources. (Neither leaked semaphores nor shared
195 memory segments will be automatically unlinked until the next reboot. This is
196 problematic for both objects because the system allows only a limited number of
197 named semaphores, and shared memory segments occupy some space in the main
198 memory.)
199
200 To select a start method you use the :func:`set_start_method` in
201 the ``if __name__ == '__main__'`` clause of the main module. For
202 example::
203
204 import multiprocessing as mp
205
206 def foo(q):
207 q.put('hello')
208
209 if __name__ == '__main__':
210 mp.set_start_method('spawn')
211 q = mp.Queue()
212 p = mp.Process(target=foo, args=(q,))
213 p.start()
214 print(q.get())
215 p.join()
216
217 :func:`set_start_method` should not be used more than once in the
218 program.
219
220 Alternatively, you can use :func:`get_context` to obtain a context
221 object. Context objects have the same API as the multiprocessing
222 module, and allow one to use multiple start methods in the same
223 program. ::
224
225 import multiprocessing as mp
226
227 def foo(q):
228 q.put('hello')
229
230 if __name__ == '__main__':
231 ctx = mp.get_context('spawn')
232 q = ctx.Queue()
233 p = ctx.Process(target=foo, args=(q,))
234 p.start()
235 print(q.get())
236 p.join()
237
238 Note that objects related to one context may not be compatible with
239 processes for a different context. In particular, locks created using
240 the *fork* context cannot be passed to processes started using the
241 *spawn* or *forkserver* start methods.
242
243 Libraries using :mod:`!multiprocessing` or
244 :class:`~concurrent.futures.ProcessPoolExecutor` should be designed to allow
245 their users to provide their own multiprocessing context. Using a specific
246 context of your own within a library can lead to incompatibilities with the
247 rest of the library user's application. Always document if your library
248 requires a specific start method.
249
250 .. warning::
251
252 The ``'spawn'`` and ``'forkserver'`` start methods generally cannot
253 be used with "frozen" executables (i.e., binaries produced by
254 packages like **PyInstaller** and **cx_Freeze**) on POSIX systems.
255 The ``'fork'`` start method may work if code does not use threads.
256
257
258 Exchanging objects between processes
259 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
260
261 :mod:`!multiprocessing` supports two types of communication channel between
262 processes:
263
264 **Queues**
265
266 The :class:`Queue` class is a near clone of :class:`queue.Queue`. For
267 example::
268
269 from multiprocessing import Process, Queue
270
271 def f(q):
272 q.put([42, None, 'hello'])
273
274 if __name__ == '__main__':
275 q = Queue()
276 p = Process(target=f, args=(q,))
277 p.start()
278 print(q.get()) # prints "[42, None, 'hello']"
279 p.join()
280
281 Queues are thread and process safe.
282 Any object put into a :mod:`!multiprocessing` queue will be serialized.
283
284 **Pipes**
285
286 The :func:`Pipe` function returns a pair of connection objects connected by a
287 pipe which by default is duplex (two-way). For example::
288
289 from multiprocessing import Process, Pipe
290
291 def f(conn):
292 conn.send([42, None, 'hello'])
293 conn.close()
294
295 if __name__ == '__main__':
296 parent_conn, child_conn = Pipe()
297 p = Process(target=f, args=(child_conn,))
298 p.start()
299 print(parent_conn.recv()) # prints "[42, None, 'hello']"
300 p.join()
301
302 The two connection objects returned by :func:`Pipe` represent the two ends of
303 the pipe. Each connection object has :meth:`~Connection.send` and
304 :meth:`~Connection.recv` methods (among others). Note that data in a pipe
305 may become corrupted if two processes (or threads) try to read from or write
306 to the *same* end of the pipe at the same time. Of course there is no risk
307 of corruption from processes using different ends of the pipe at the same
308 time.
309
310 The :meth:`~Connection.send` method serializes the object and
311 :meth:`~Connection.recv` re-creates the object.
312
313 Synchronization between processes
314 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
315
316 :mod:`!multiprocessing` contains equivalents of all the synchronization
317 primitives from :mod:`threading`. For instance one can use a lock to ensure
318 that only one process prints to standard output at a time::
319
320 from multiprocessing import Process, Lock
321
322 def f(l, i):
323 l.acquire()
324 try:
325 print('hello world', i)
326 finally:
327 l.release()
328
329 if __name__ == '__main__':
330 lock = Lock()
331
332 for num in range(10):
333 Process(target=f, args=(lock, num)).start()
334
335 Without using the lock output from the different processes is liable to get all
336 mixed up.
337
338
339 Sharing state between processes
340 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341
342 As mentioned above, when doing concurrent programming it is usually best to
343 avoid using shared state as far as possible. This is particularly true when
344 using multiple processes.
345
346 However, if you really do need to use some shared data then
347 :mod:`!multiprocessing` provides a couple of ways of doing so.
348
349 **Shared memory**
350
351 Data can be stored in a shared memory map using :class:`Value` or
352 :class:`Array`. For example, the following code ::
353
354 from multiprocessing import Process, Value, Array
355
356 def f(n, a):
357 n.value = 3.1415927
358 for i in range(len(a)):
359 a[i] = -a[i]
360
361 if __name__ == '__main__':
362 num = Value('d', 0.0)
363 arr = Array('i', range(10))
364
365 p = Process(target=f, args=(num, arr))
366 p.start()
367 p.join()
368
369 print(num.value)
370 print(arr[:])
371
372 will print ::
373
374 3.1415927
375 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
376
377 The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
378 typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
379 double precision float and ``'i'`` indicates a signed integer. These shared
380 objects will be process and thread-safe.
381
382 For more flexibility in using shared memory one can use the
383 :mod:`multiprocessing.sharedctypes` module which supports the creation of
384 arbitrary ctypes objects allocated from shared memory.
385
386 **Server process**
387
388 A manager object returned by :func:`Manager` controls a server process which
389 holds Python objects and allows other processes to manipulate them using
390 proxies.
391
392 A manager returned by :func:`Manager` will support types
393 :class:`list`, :class:`dict`, :class:`set`, :class:`~managers.Namespace`, :class:`Lock`,
394 :class:`RLock`, :class:`Semaphore`, :class:`BoundedSemaphore`,
395 :class:`Condition`, :class:`Event`, :class:`Barrier`,
396 :class:`Queue`, :class:`Value` and :class:`Array`. For example, ::
397
398 from multiprocessing import Process, Manager
399
400 def f(d, l, s):
401 d[1] = '1'
402 d['2'] = 2
403 d[0.25] = None
404 l.reverse()
405 s.add('a')
406 s.add('b')
407
408 if __name__ == '__main__':
409 with Manager() as manager:
410 d = manager.dict()
411 l = manager.list(range(10))
412 s = manager.set()
413
414 p = Process(target=f, args=(d, l, s))
415 p.start()
416 p.join()
417
418 print(d)
419 print(l)
420 print(s)
421
422 will print ::
423
424 {0.25: None, 1: '1', '2': 2}
425 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
426 {'a', 'b'}
427
428 Server process managers are more flexible than using shared memory objects
429 because they can be made to support arbitrary object types. Also, a single
430 manager can be shared by processes on different computers over a network.
431 They are, however, slower than using shared memory.
432
433
434 Using a pool of workers
435 ^^^^^^^^^^^^^^^^^^^^^^^
436
437 The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
438 processes. It has methods which allows tasks to be offloaded to the worker
439 processes in a few different ways.
440
441 For example::
442
443 from multiprocessing import Pool, TimeoutError
444 import time
445 import os
446
447 def f(x):
448 return x*x
449
450 if __name__ == '__main__':
451 # start 4 worker processes
452 with Pool(processes=4) as pool:
453
454 # print "[0, 1, 4,..., 81]"
455 print(pool.map(f, range(10)))
456
457 # print same numbers in arbitrary order
458 for i in pool.imap_unordered(f, range(10)):
459 print(i)
460
461 # evaluate "f(20)" asynchronously
462 res = pool.apply_async(f, (20,)) # runs in *only* one process
463 print(res.get(timeout=1)) # prints "400"
464
465 # evaluate "os.getpid()" asynchronously
466 res = pool.apply_async(os.getpid, ()) # runs in *only* one process
467 print(res.get(timeout=1)) # prints the PID of that process
468
469 # launching multiple evaluations asynchronously *may* use more processes
470 multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
471 print([res.get(timeout=1) for res in multiple_results])
472
473 # make a single worker sleep for 10 seconds
474 res = pool.apply_async(time.sleep, (10,))
475 try:
476 print(res.get(timeout=1))
477 except TimeoutError:
478 print("We lacked patience and got a multiprocessing.TimeoutError")
479
480 print("For the moment, the pool remains available for more work")
481
482 # exiting the 'with'-block has stopped the pool
483 print("Now the pool is closed and no longer available")
484
485 Note that the methods of a pool should only ever be used by the
486 process which created it.
487
488 .. note::
489
490 Functionality within this package requires that the ``__main__`` module be
491 importable by the children. This is covered in :ref:`multiprocessing-programming`
492 however it is worth pointing out here. This means that some examples, such
493 as the :class:`multiprocessing.pool.Pool` examples will not work in the
494 interactive interpreter. For example::
495
496 >>> from multiprocessing import Pool
497 >>> p = Pool(5)
498 >>> def f(x):
499 ... return x*x
500 ...
501 >>> with p:
502 ... p.map(f, [1,2,3])
503 Process PoolWorker-1:
504 Process PoolWorker-2:
505 Process PoolWorker-3:
506 Traceback (most recent call last):
507 Traceback (most recent call last):
508 Traceback (most recent call last):
509 AttributeError: Can't get attribute 'f' on <module '__main__' (<class '_frozen_importlib.BuiltinImporter'>)>
510 AttributeError: Can't get attribute 'f' on <module '__main__' (<class '_frozen_importlib.BuiltinImporter'>)>
511 AttributeError: Can't get attribute 'f' on <module '__main__' (<class '_frozen_importlib.BuiltinImporter'>)>
512
513 (If you try this it will actually output three full tracebacks
514 interleaved in a semi-random fashion, and then you may have to
515 stop the parent process somehow.)
516
517
518 Reference
519 ---------
520
521 The :mod:`!multiprocessing` package mostly replicates the API of the
522 :mod:`threading` module.
523
524 .. _global-start-method:
525
526 Global start method
527 ^^^^^^^^^^^^^^^^^^^
528
529 Python supports several ways to create and initialize a process.
530 The global start method sets the default mechanism for creating a process.
531
532 Several multiprocessing functions and methods that may also instantiate
533 certain objects will implicitly set the global start method to the system's default,
534 if it hasn’t been set already. The global start method can only be set once.
535 If you need to change the start method from the system default, you must
536 proactively set the global start method before calling functions or methods,
537 or creating these objects.
538
539
540 :class:`Process` and exceptions
541 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
542
543 .. class:: Process(group=None, target=None, name=None, args=(), kwargs={}, \
544 *, daemon=None)
545
546 Process objects represent activity that is run in a separate process. The
547 :class:`Process` class has equivalents of all the methods of
548 :class:`threading.Thread`.
549
550 The constructor should always be called with keyword arguments. *group*
551 should always be ``None``; it exists solely for compatibility with
552 :class:`threading.Thread`. *target* is the callable object to be invoked by
553 the :meth:`run` method. It defaults to ``None``, meaning nothing is
554 called. *name* is the process name (see :attr:`name` for more details).
555 *args* is the argument tuple for the target invocation. *kwargs* is a
556 dictionary of keyword arguments for the target invocation. If provided,
557 the keyword-only *daemon* argument sets the process :attr:`daemon` flag
558 to ``True`` or ``False``. If ``None`` (the default), this flag will be
559 inherited from the creating process.
560
561 By default, no arguments are passed to *target*. The *args* argument,
562 which defaults to ``()``, can be used to specify a list or tuple of the arguments
563 to pass to *target*.
564
565 If a subclass overrides the constructor, it must make sure it invokes the
566 base class constructor (``super().__init__()``) before doing anything else
567 to the process.
568
569 .. note::
570
571 In general, all arguments to :class:`Process` must be picklable. This is
572 frequently observed when trying to create a :class:`Process` or use a
573 :class:`concurrent.futures.ProcessPoolExecutor` from a REPL with a
574 locally defined *target* function.
575
576 Passing a callable object defined in the current REPL session causes the
577 child process to die via an uncaught :exc:`AttributeError` exception when
578 starting as *target* must have been defined within an importable module
579 in order to be loaded during unpickling.
580
581 Example of this uncatchable error from the child::
582
583 >>> import multiprocessing as mp
584 >>> def knigit():
585 ... print("Ni!")
586 ...
587 >>> process = mp.Process(target=knigit)
588 >>> process.start()
589 >>> Traceback (most recent call last):
590 File ".../multiprocessing/spawn.py", line ..., in spawn_main
591 File ".../multiprocessing/spawn.py", line ..., in _main
592 AttributeError: module '__main__' has no attribute 'knigit'
593 >>> process
594 <SpawnProcess name='SpawnProcess-1' pid=379473 parent=378707 stopped exitcode=1>
595
596 See :ref:`multiprocessing-programming-spawn`. While this restriction is
597 not true if using the ``"fork"`` start method, as of Python ``3.14`` that
598 is no longer the default on any platform. See
599 :ref:`multiprocessing-start-methods`.
600 See also :gh:`132898`.
601
602 .. versionchanged:: 3.3
603 Added the *daemon* parameter.
604
605 .. method:: run()
606
607 Method representing the process's activity.
608
609 You may override this method in a subclass. The standard :meth:`run`
610 method invokes the callable object passed to the object's constructor as
611 the target argument, if any, with sequential and keyword arguments taken
612 from the *args* and *kwargs* arguments, respectively.
613
614 Using a list or tuple as the *args* argument passed to :class:`Process`
615 achieves the same effect.
616
617 Example::
618
619 >>> from multiprocessing import Process
620 >>> p = Process(target=print, args=[1])
621 >>> p.run()
622 1
623 >>> p = Process(target=print, args=(1,))
624 >>> p.run()
625 1
626
627 .. method:: start()
628
629 Start the process's activity.
630
631 This must be called at most once per process object. It arranges for the
632 object's :meth:`run` method to be invoked in a separate process.
633
634 .. method:: join([timeout])
635
636 If the optional argument *timeout* is ``None`` (the default), the method
637 blocks until the process whose :meth:`join` method is called terminates.
638 If *timeout* is a positive number, it blocks at most *timeout* seconds.
639 Note that the method returns ``None`` if its process terminates or if the
640 method times out. Check the process's :attr:`exitcode` to determine if
641 it terminated.
642
643 A process can be joined many times.
644
645 A process cannot join itself because this would cause a deadlock. It is
646 an error to attempt to join a process before it has been started.
647
648 .. attribute:: name
649
650 The process's name. The name is a string used for identification purposes
651 only. It has no semantics. Multiple processes may be given the same
652 name.
653
654 The initial name is set by the constructor. If no explicit name is
655 provided to the constructor, a name of the form
656 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' is constructed, where
657 each N\ :sub:`k` is the N-th child of its parent.
658
659 .. method:: is_alive
660
661 Return whether the process is alive.
662
663 Roughly, a process object is alive from the moment the :meth:`start`
664 method returns until the child process terminates.
665
666 .. attribute:: daemon
667
668 The process's daemon flag, a Boolean value. This must be set before
669 :meth:`start` is called.
670
671 The initial value is inherited from the creating process.
672
673 When a process exits, it attempts to terminate all of its daemonic child
674 processes.
675
676 Note that a daemonic process is not allowed to create child processes.
677 Otherwise a daemonic process would leave its children orphaned if it gets
678 terminated when its parent process exits. Additionally, these are **not**
679 Unix daemons or services, they are normal processes that will be
680 terminated (and not joined) if non-daemonic processes have exited.
681
682 In addition to the :class:`threading.Thread` API, :class:`Process` objects
683 also support the following attributes and methods:
684
685 .. attribute:: pid
686
687 Return the process ID. Before the process is spawned, this will be
688 ``None``.
689
690 .. attribute:: exitcode
691
692 The child's exit code. This will be ``None`` if the process has not yet
693 terminated.
694
695 If the child's :meth:`run` method returned normally, the exit code
696 will be 0. If it terminated via :func:`sys.exit` with an integer
697 argument *N*, the exit code will be *N*.
698
699 If the child terminated due to an exception not caught within
700 :meth:`run`, the exit code will be 1. If it was terminated by
701 signal *N*, the exit code will be the negative value *-N*.
702
703 .. attribute:: authkey
704
705 The process's authentication key (a byte string).
706
707 When :mod:`!multiprocessing` is initialized the main process is assigned a
708 random string using :func:`os.urandom`.
709
710 When a :class:`Process` object is created, it will inherit the
711 authentication key of its parent process, although this may be changed by
712 setting :attr:`authkey` to another byte string.
713
714 See :ref:`multiprocessing-auth-keys`.
715
716 .. attribute:: sentinel
717
718 A numeric handle of a system object which will become "ready" when
719 the process ends.
720
721 You can use this value if you want to wait on several events at
722 once using :func:`multiprocessing.connection.wait`. Otherwise
723 calling :meth:`join` is simpler.
724
725 On Windows, this is an OS handle usable with the ``WaitForSingleObject``
726 and ``WaitForMultipleObjects`` family of API calls. On POSIX, this is
727 a file descriptor usable with primitives from the :mod:`select` module.
728
729 .. versionadded:: 3.3
730
731 .. method:: interrupt()
732
733 Terminate the process. Works on POSIX using the :py:const:`~signal.SIGINT` signal.
734 Behavior on Windows is undefined.
735
736 By default, this terminates the child process by raising :exc:`KeyboardInterrupt`.
737 This behavior can be altered by setting the respective signal handler in the child
738 process :func:`signal.signal` for :py:const:`~signal.SIGINT`.
739
740 Note: if the child process catches and discards :exc:`KeyboardInterrupt`, the
741 process will not be terminated.
742
743 Note: the default behavior will also set :attr:`exitcode` to ``1`` as if an
744 uncaught exception was raised in the child process. To have a different
745 :attr:`exitcode` you may simply catch :exc:`KeyboardInterrupt` and call
746 ``exit(your_code)``.
747
748 .. versionadded:: 3.14
749
750 .. method:: terminate()
751
752 Terminate the process. On POSIX this is done using the :py:const:`~signal.SIGTERM` signal;
753 on Windows :c:func:`!TerminateProcess` is used. Note that exit handlers and
754 finally clauses, etc., will not be executed.
755
756 Note that descendant processes of the process will *not* be terminated --
757 they will simply become orphaned.
758
759 .. warning::
760
761 If this method is used when the associated process is using a pipe or
762 queue then the pipe or queue is liable to become corrupted and may
763 become unusable by other process. Similarly, if the process has
764 acquired a lock or semaphore etc. then terminating it is liable to
765 cause other processes to deadlock.
766
767 .. method:: kill()
768
769 Same as :meth:`terminate` but using the ``SIGKILL`` signal on POSIX.
770
771 .. versionadded:: 3.7
772
773 .. method:: close()
774
775 Close the :class:`Process` object, releasing all resources associated
776 with it. :exc:`ValueError` is raised if the underlying process
777 is still running. Once :meth:`close` returns successfully, most
778 other methods and attributes of the :class:`Process` object will
779 raise :exc:`ValueError`.
780
781 .. versionadded:: 3.7
782
783 Note that the :meth:`start`, :meth:`join`, :meth:`is_alive`,
784 :meth:`terminate` and :attr:`exitcode` methods should only be called by
785 the process that created the process object.
786
787 Example usage of some of the methods of :class:`Process`:
788
789 .. doctest::
790
791 >>> import multiprocessing, time, signal
792 >>> mp_context = multiprocessing.get_context('spawn')
793 >>> p = mp_context.Process(target=time.sleep, args=(1000,))
794 >>> print(p, p.is_alive())
795 <...Process ... initial> False
796 >>> p.start()
797 >>> print(p, p.is_alive())
798 <...Process ... started> True
799 >>> p.terminate()
800 >>> time.sleep(0.1)
801 >>> print(p, p.is_alive())
802 <...Process ... stopped exitcode=-SIGTERM> False
803 >>> p.exitcode == -signal.SIGTERM
804 True
805
806 .. exception:: ProcessError
807
808 The base class of all :mod:`!multiprocessing` exceptions.
809
810 .. exception:: BufferTooShort
811
812 Exception raised by :meth:`Connection.recv_bytes_into` when the supplied
813 buffer object is too small for the message read.
814
815 If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
816 the message as a byte string.
817
818 .. exception:: AuthenticationError
819
820 Raised when there is an authentication error.
821
822 .. exception:: TimeoutError
823
824 Raised by methods with a timeout when the timeout expires.
825
826 Pipes and Queues
827 ^^^^^^^^^^^^^^^^
828
829 When using multiple processes, one generally uses message passing for
830 communication between processes and avoids having to use any synchronization
831 primitives like locks.
832
833 For passing messages one can use :func:`Pipe` (for a connection between two
834 processes) or a queue (which allows multiple producers and consumers).
835
836 The :class:`Queue`, :class:`SimpleQueue` and :class:`JoinableQueue` types
837 are multi-producer, multi-consumer :abbr:`FIFO (first-in, first-out)`
838 queues modelled on the :class:`queue.Queue` class in the
839 standard library. They differ in that :class:`Queue` lacks the
840 :meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join` methods introduced
841 into Python 2.5's :class:`queue.Queue` class.
842
843 If you use :class:`JoinableQueue` then you **must** call
844 :meth:`JoinableQueue.task_done` for each task removed from the queue or else the
845 semaphore used to count the number of unfinished tasks may eventually overflow,
846 raising an exception.
847
848 One difference from other Python queue implementations, is that :mod:`!multiprocessing`
849 queues serializes all objects that are put into them using :mod:`pickle`.
850 The object returned by the get method is a re-created object that does not share
851 memory with the original object.
852
853 Note that one can also create a shared queue by using a manager object -- see
854 :ref:`multiprocessing-managers`.
855
856 .. note::
857
858 :mod:`!multiprocessing` uses the usual :exc:`queue.Empty` and
859 :exc:`queue.Full` exceptions to signal a timeout. They are not available in
860 the :mod:`!multiprocessing` namespace so you need to import them from
861 :mod:`queue`.
862
863 .. note::
864
865 When an object is put on a queue, the object is pickled and a
866 background thread later flushes the pickled data to an underlying
867 pipe. This has some consequences which are a little surprising,
868 but should not cause any practical difficulties -- if they really
869 bother you then you can instead use a queue created with a
870 :ref:`manager <multiprocessing-managers>`.
871
872 (1) After putting an object on an empty queue there may be an
873 infinitesimal delay before the queue's :meth:`~Queue.empty`
874 method returns :const:`False` and :meth:`~Queue.get_nowait` can
875 return without raising :exc:`queue.Empty`.
876
877 (2) If multiple processes are enqueuing objects, it is possible for
878 the objects to be received at the other end out-of-order.
879 However, objects enqueued by the same process will always be in
880 the expected order with respect to each other.
881
882 .. warning::
883
884 If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
885 while it is trying to use a :class:`Queue`, then the data in the queue is
886 likely to become corrupted. This may cause any other process to get an
887 exception when it tries to use the queue later on.
888
889 .. warning::
890
891 As mentioned above, if a child process has put items on a queue (and it has
892 not used :meth:`JoinableQueue.cancel_join_thread
893 <multiprocessing.Queue.cancel_join_thread>`), then that process will
894 not terminate until all buffered items have been flushed to the pipe.
895
896 This means that if you try joining that process you may get a deadlock unless
897 you are sure that all items which have been put on the queue have been
898 consumed. Similarly, if the child process is non-daemonic then the parent
899 process may hang on exit when it tries to join all its non-daemonic children.
900
901 Note that a queue created using a manager does not have this issue. See
902 :ref:`multiprocessing-programming`.
903
904 For an example of the usage of queues for interprocess communication see
905 :ref:`multiprocessing-examples`.
906
907
908 .. function:: Pipe(duplex=True)
909
910 Returns a pair ``(conn1, conn2)`` of
911 :class:`~multiprocessing.connection.Connection` objects representing the
912 ends of a pipe.
913
914 If *duplex* is ``True`` (the default) then the pipe is bidirectional. If
915 *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
916 used for receiving messages and ``conn2`` can only be used for sending
917 messages.
918
919 The :meth:`~multiprocessing.Connection.send` method serializes the object using
920 :mod:`pickle` and the :meth:`~multiprocessing.Connection.recv` re-creates the object.
921
922 .. class:: Queue([maxsize])
923
924 Returns a process shared queue implemented using a pipe and a few
925 locks/semaphores. When a process first puts an item on the queue a feeder
926 thread is started which transfers objects from a buffer into the pipe.
927
928 Instantiating this class may set the global start method. See
929 :ref:`global-start-method` for more details.
930
931 The usual :exc:`queue.Empty` and :exc:`queue.Full` exceptions from the
932 standard library's :mod:`queue` module are raised to signal timeouts.
933
934 :class:`Queue` implements all the methods of :class:`queue.Queue` except for
935 :meth:`~queue.Queue.task_done`, :meth:`~queue.Queue.join`, and
936 :meth:`~queue.Queue.shutdown`.
937
938 .. method:: qsize()
939
940 Return the approximate size of the queue. Because of
941 multithreading/multiprocessing semantics, this number is not reliable.
942
943 Note that this may raise :exc:`NotImplementedError` on platforms like
944 macOS where ``sem_getvalue()`` is not implemented.
945
946 .. method:: empty()
947
948 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
949 multithreading/multiprocessing semantics, this is not reliable.
950
951 May raise an :exc:`OSError` on closed queues. (not guaranteed)
952
953 .. method:: full()
954
955 Return ``True`` if the queue is full, ``False`` otherwise. Because of
956 multithreading/multiprocessing semantics, this is not reliable.
957
958 .. method:: put(obj[, block[, timeout]])
959
960 Put obj into the queue. If the optional argument *block* is ``True``
961 (the default) and *timeout* is ``None`` (the default), block if necessary until
962 a free slot is available. If *timeout* is a positive number, it blocks at
963 most *timeout* seconds and raises the :exc:`queue.Full` exception if no
964 free slot was available within that time. Otherwise (*block* is
965 ``False``), put an item on the queue if a free slot is immediately
966 available, else raise the :exc:`queue.Full` exception (*timeout* is
967 ignored in that case).
968
969 .. versionchanged:: 3.8
970 If the queue is closed, :exc:`ValueError` is raised instead of
971 :exc:`AssertionError`.
972
973 .. method:: put_nowait(obj)
974
975 Equivalent to ``put(obj, False)``.
976
977 .. method:: get([block[, timeout]])
978
979 Remove and return an item from the queue. If optional args *block* is
980 ``True`` (the default) and *timeout* is ``None`` (the default), block if
981 necessary until an item is available. If *timeout* is a positive number,
982 it blocks at most *timeout* seconds and raises the :exc:`queue.Empty`
983 exception if no item was available within that time. Otherwise (block is
984 ``False``), return an item if one is immediately available, else raise the
985 :exc:`queue.Empty` exception (*timeout* is ignored in that case).
986
987 .. versionchanged:: 3.8
988 If the queue is closed, :exc:`ValueError` is raised instead of
989 :exc:`OSError`.
990
991 .. method:: get_nowait()
992
993 Equivalent to ``get(False)``.
994
995 :class:`multiprocessing.Queue` has a few additional methods not found in
996 :class:`queue.Queue`. These methods are usually unnecessary for most
997 code:
998
999 .. method:: close()
1000
1001 Close the queue: release internal resources.
1002
1003 A queue must not be used anymore after it is closed. For example,
1004 :meth:`~Queue.get`, :meth:`~Queue.put` and :meth:`~Queue.empty`
1005 methods must no longer be called.
1006
1007 The background thread will quit once it has flushed all buffered
1008 data to the pipe. This is called automatically when the queue is garbage
1009 collected.
1010
1011 .. method:: join_thread()
1012
1013 Join the background thread. This can only be used after :meth:`close` has
1014 been called. It blocks until the background thread exits, ensuring that
1015 all data in the buffer has been flushed to the pipe.
1016
1017 By default if a process is not the creator of the queue then on exit it
1018 will attempt to join the queue's background thread. The process can call
1019 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
1020
1021 .. method:: cancel_join_thread()
1022
1023 Prevent :meth:`join_thread` from blocking. In particular, this prevents
1024 the background thread from being joined automatically when the process
1025 exits -- see :meth:`join_thread`.
1026
1027 A better name for this method might be
1028 ``allow_exit_without_flush()``. It is likely to cause enqueued
1029 data to be lost, and you almost certainly will not need to use it.
1030 It is really only there if you need the current process to exit
1031 immediately without waiting to flush enqueued data to the
1032 underlying pipe, and you don't care about lost data.
1033
1034 .. note::
1035
1036 This class's functionality requires a functioning shared semaphore
1037 implementation on the host operating system. Without one, the
1038 functionality in this class will be disabled, and attempts to
1039 instantiate a :class:`Queue` will result in an :exc:`ImportError`. See
1040 :issue:`3770` for additional information. The same holds true for any
1041 of the specialized queue types listed below.
1042
1043 .. class:: SimpleQueue()
1044
1045 It is a simplified :class:`Queue` type, very close to a locked :class:`Pipe`.
1046
1047 Instantiating this class may set the global start method. See
1048 :ref:`global-start-method` for more details.
1049
1050 .. method:: close()
1051
1052 Close the queue: release internal resources.
1053
1054 A queue must not be used anymore after it is closed. For example,
1055 :meth:`get`, :meth:`put` and :meth:`empty` methods must no longer be
1056 called.
1057
1058 .. versionadded:: 3.9
1059
1060 .. method:: empty()
1061
1062 Return ``True`` if the queue is empty, ``False`` otherwise.
1063
1064 Always raises an :exc:`OSError` if the SimpleQueue is closed.
1065
1066 .. method:: get()
1067
1068 Remove and return an item from the queue.
1069
1070 .. method:: put(item)
1071
1072 Put *item* into the queue.
1073
1074
1075 .. class:: JoinableQueue([maxsize])
1076
1077 :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which
1078 additionally has :meth:`task_done` and :meth:`join` methods.
1079
1080 Instantiating this class may set the global start method. See
1081 :ref:`global-start-method` for more details.
1082
1083 .. method:: task_done()
1084
1085 Indicate that a formerly enqueued task is complete. Used by queue
1086 consumers. For each :meth:`~Queue.get` used to fetch a task, a subsequent
1087 call to :meth:`task_done` tells the queue that the processing on the task
1088 is complete.
1089
1090 If a :meth:`~queue.Queue.join` is currently blocking, it will resume when all
1091 items have been processed (meaning that a :meth:`task_done` call was
1092 received for every item that had been :meth:`~Queue.put` into the queue).
1093
1094 Raises a :exc:`ValueError` if called more times than there were items
1095 placed in the queue.
1096
1097
1098 .. method:: join()
1099
1100 Block until all items in the queue have been gotten and processed.
1101
1102 The count of unfinished tasks goes up whenever an item is added to the
1103 queue. The count goes down whenever a consumer calls
1104 :meth:`task_done` to indicate that the item was retrieved and all work on
1105 it is complete. When the count of unfinished tasks drops to zero,
1106 :meth:`~queue.Queue.join` unblocks.
1107
1108
1109 Miscellaneous
1110 ^^^^^^^^^^^^^
1111
1112 .. function:: active_children()
1113
1114 Return list of all live children of the current process.
1115
1116 Calling this has the side effect of "joining" any processes which have
1117 already finished.
1118
1119 .. function:: cpu_count()
1120
1121 Return the number of CPUs in the system.
1122
1123 This number is not equivalent to the number of CPUs the current process can
1124 use. The number of usable CPUs can be obtained with
1125 :func:`os.process_cpu_count` (or ``len(os.sched_getaffinity(0))``).
1126
1127 When the number of CPUs cannot be determined a :exc:`NotImplementedError`
1128 is raised.
1129
1130 .. seealso::
1131 :func:`os.cpu_count`
1132 :func:`os.process_cpu_count`
1133
1134 .. versionchanged:: 3.13
1135
1136 The return value can also be overridden using the
1137 :option:`-X cpu_count <-X>` flag or :envvar:`PYTHON_CPU_COUNT` as this is
1138 merely a wrapper around the :mod:`os` cpu count APIs.
1139
1140 .. function:: current_process()
1141
1142 Return the :class:`Process` object corresponding to the current process.
1143
1144 An analogue of :func:`threading.current_thread`.
1145
1146 .. function:: parent_process()
1147
1148 Return the :class:`Process` object corresponding to the parent process of
1149 the :func:`current_process`. For the main process, ``parent_process`` will
1150 be ``None``.
1151
1152 .. versionadded:: 3.8
1153
1154 .. function:: freeze_support()
1155
1156 Add support for when a program which uses :mod:`!multiprocessing` has been
1157 frozen to produce an executable. (Has been tested with **py2exe**,
1158 **PyInstaller** and **cx_Freeze**.)
1159
1160 One needs to call this function straight after the ``if __name__ ==
1161 '__main__'`` line of the main module. For example::
1162
1163 from multiprocessing import Process, freeze_support
1164
1165 def f():
1166 print('hello world!')
1167
1168 if __name__ == '__main__':
1169 freeze_support()
1170 Process(target=f).start()
1171
1172 If the ``freeze_support()`` line is omitted then trying to run the frozen
1173 executable will raise :exc:`RuntimeError`.
1174
1175 Calling ``freeze_support()`` has no effect when the start method is not
1176 *spawn*. In addition, if the module is being run normally by the Python
1177 interpreter (the program has not been frozen), then ``freeze_support()``
1178 has no effect.
1179
1180 .. function:: get_all_start_methods()
1181
1182 Returns a list of the supported start methods, the first of which
1183 is the default. The possible start methods are ``'fork'``,
1184 ``'spawn'`` and ``'forkserver'``. Not all platforms support all
1185 methods. See :ref:`multiprocessing-start-methods`.
1186
1187 .. versionadded:: 3.4
1188
1189 .. function:: get_context(method=None)
1190
1191 Return a context object which has the same attributes as the
1192 :mod:`!multiprocessing` module.
1193
1194 If *method* is ``None`` then the default context is returned. Note that if
1195 the global start method has not been set, this will set it to the system default
1196 See :ref:`global-start-method` for more details.
1197 Otherwise *method* should be ``'fork'``, ``'spawn'``,
1198 ``'forkserver'``. :exc:`ValueError` is raised if the specified
1199 start method is not available. See :ref:`multiprocessing-start-methods`.
1200
1201 .. versionadded:: 3.4
1202
1203 .. function:: get_start_method(allow_none=False)
1204
1205 Return the name of start method used for starting processes.
1206
1207 If the global start method is not set and *allow_none* is ``False``, the global start
1208 method is set to the default, and its name is returned. See
1209 :ref:`global-start-method` for more details.
1210
1211 The return value can be ``'fork'``, ``'spawn'``, ``'forkserver'``
1212 or ``None``. See :ref:`multiprocessing-start-methods`.
1213
1214 .. versionadded:: 3.4
1215
1216 .. versionchanged:: 3.8
1217
1218 On macOS, the *spawn* start method is now the default. The *fork* start
1219 method should be considered unsafe as it can lead to crashes of the
1220 subprocess. See :issue:`33725`.
1221
1222 .. function:: set_executable(executable)
1223
1224 Set the path of the Python interpreter to use when starting a child process.
1225 (By default :data:`sys.executable` is used). Embedders will probably need to
1226 do something like ::
1227
1228 set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
1229
1230 before they can create child processes.
1231
1232 .. versionchanged:: 3.4
1233 Now supported on POSIX when the ``'spawn'`` start method is used.
1234
1235 .. versionchanged:: 3.11
1236 Accepts a :term:`path-like object`.
1237
1238 .. function:: set_forkserver_preload(module_names)
1239
1240 Set a list of module names for the forkserver main process to attempt to
1241 import so that their already imported state is inherited by forked
1242 processes. Any :exc:`ImportError` when doing so is silently ignored.
1243 This can be used as a performance enhancement to avoid repeated work
1244 in every process.
1245
1246 For this to work, it must be called before the forkserver process has been
1247 launched (before creating a :class:`Pool` or starting a :class:`Process`).
1248
1249 Only meaningful when using the ``'forkserver'`` start method.
1250 See :ref:`multiprocessing-start-methods`.
1251
1252 .. versionadded:: 3.4
1253
1254 .. function:: set_start_method(method, force=False)
1255
1256 Set the method which should be used to start child processes.
1257 The *method* argument can be ``'fork'``, ``'spawn'`` or ``'forkserver'``.
1258 Raises :exc:`RuntimeError` if the start method has already been set and *force*
1259 is not ``True``. If *method* is ``None`` and *force* is ``True`` then the start
1260 method is set to ``None``. If *method* is ``None`` and *force* is ``False``
1261 then the context is set to the default context.
1262
1263 Note that this should be called at most once, and it should be
1264 protected inside the ``if __name__ == '__main__'`` clause of the
1265 main module.
1266
1267 See :ref:`multiprocessing-start-methods`.
1268
1269 .. versionadded:: 3.4
1270
1271 .. note::
1272
1273 :mod:`!multiprocessing` contains no analogues of
1274 :func:`threading.active_count`, :func:`threading.enumerate`,
1275 :func:`threading.settrace`, :func:`threading.setprofile`,
1276 :class:`threading.Timer`, or :class:`threading.local`.
1277
1278
1279 Connection Objects
1280 ^^^^^^^^^^^^^^^^^^
1281
1282 .. currentmodule:: multiprocessing.connection
1283
1284 Connection objects allow the sending and receiving of picklable objects or
1285 strings. They can be thought of as message oriented connected sockets.
1286
1287 Connection objects are usually created using
1288 :func:`Pipe <multiprocessing.Pipe>` -- see also
1289 :ref:`multiprocessing-listeners-clients`.
1290
1291 .. class:: Connection
1292
1293 .. method:: send(obj)
1294
1295 Send an object to the other end of the connection which should be read
1296 using :meth:`recv`.
1297
1298 The object must be picklable. Very large pickles (approximately 32 MiB+,
1299 though it depends on the OS) may raise a :exc:`ValueError` exception.
1300
1301 .. method:: recv()
1302
1303 Return an object sent from the other end of the connection using
1304 :meth:`send`. Blocks until there is something to receive. Raises
1305 :exc:`EOFError` if there is nothing left to receive
1306 and the other end was closed.
1307
1308 .. method:: fileno()
1309
1310 Return the file descriptor or handle used by the connection.
1311
1312 .. method:: close()
1313
1314 Close the connection.
1315
1316 This is called automatically when the connection is garbage collected.
1317
1318 .. method:: poll([timeout])
1319
1320 Return whether there is any data available to be read.
1321
1322 If *timeout* is not specified then it will return immediately. If
1323 *timeout* is a number then this specifies the maximum time in seconds to
1324 block. If *timeout* is ``None`` then an infinite timeout is used.
1325
1326 Note that multiple connection objects may be polled at once by
1327 using :func:`multiprocessing.connection.wait`.
1328
1329 .. method:: send_bytes(buf[, offset[, size]])
1330
1331 Send byte data from a :term:`bytes-like object` as a complete message.
1332
1333 If *offset* is given then data is read from that position in *buf*. If
1334 *size* is given then that many bytes will be read from *buf*. Very large
1335 buffers (approximately 32 MiB+, though it depends on the OS) may raise a
1336 :exc:`ValueError` exception
1337
1338 .. method:: recv_bytes([maxlength])
1339
1340 Return a complete message of byte data sent from the other end of the
1341 connection as a string. Blocks until there is something to receive.
1342 Raises :exc:`EOFError` if there is nothing left
1343 to receive and the other end has closed.
1344
1345 If *maxlength* is specified and the message is longer than *maxlength*
1346 then :exc:`OSError` is raised and the connection will no longer be
1347 readable.
1348
1349 .. versionchanged:: 3.3
1350 This function used to raise :exc:`IOError`, which is now an
1351 alias of :exc:`OSError`.
1352
1353
1354 .. method:: recv_bytes_into(buf[, offset])
1355
1356 Read into *buf* a complete message of byte data sent from the other end
1357 of the connection and return the number of bytes in the message. Blocks
1358 until there is something to receive. Raises
1359 :exc:`EOFError` if there is nothing left to receive and the other end was
1360 closed.
1361
1362 *buf* must be a writable :term:`bytes-like object`. If
1363 *offset* is given then the message will be written into the buffer from
1364 that position. Offset must be a non-negative integer less than the
1365 length of *buf* (in bytes).
1366
1367 If the buffer is too short then a :exc:`BufferTooShort` exception is
1368 raised and the complete message is available as ``e.args[0]`` where ``e``
1369 is the exception instance.
1370
1371 .. versionchanged:: 3.3
1372 Connection objects themselves can now be transferred between processes
1373 using :meth:`Connection.send` and :meth:`Connection.recv`.
1374
1375 Connection objects also now support the context management protocol -- see
1376 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the
1377 connection object, and :meth:`~contextmanager.__exit__` calls :meth:`close`.
1378
1379 For example:
1380
1381 .. doctest::
1382
1383 >>> from multiprocessing import Pipe
1384 >>> a, b = Pipe()
1385 >>> a.send([1, 'hello', None])
1386 >>> b.recv()
1387 [1, 'hello', None]
1388 >>> b.send_bytes(b'thank you')
1389 >>> a.recv_bytes()
1390 b'thank you'
1391 >>> import array
1392 >>> arr1 = array.array('i', range(5))
1393 >>> arr2 = array.array('i', [0] * 10)
1394 >>> a.send_bytes(arr1)
1395 >>> count = b.recv_bytes_into(arr2)
1396 >>> assert count == len(arr1) * arr1.itemsize
1397 >>> arr2
1398 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
1399
1400 .. _multiprocessing-recv-pickle-security:
1401
1402 .. warning::
1403
1404 The :meth:`Connection.recv` method automatically unpickles the data it
1405 receives, which can be a security risk unless you can trust the process
1406 which sent the message.
1407
1408 Therefore, unless the connection object was produced using :func:`Pipe` you
1409 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
1410 methods after performing some sort of authentication. See
1411 :ref:`multiprocessing-auth-keys`.
1412
1413 .. warning::
1414
1415 If a process is killed while it is trying to read or write to a pipe then
1416 the data in the pipe is likely to become corrupted, because it may become
1417 impossible to be sure where the message boundaries lie.
1418
1419
1420 Synchronization primitives
1421 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1422
1423 .. currentmodule:: multiprocessing
1424
1425 Generally synchronization primitives are not as necessary in a multiprocess
1426 program as they are in a multithreaded program. See the documentation for
1427 :mod:`threading` module.
1428
1429 Note that one can also create synchronization primitives by using a manager
1430 object -- see :ref:`multiprocessing-managers`.
1431
1432 .. class:: Barrier(parties[, action[, timeout]])
1433
1434 A barrier object: a clone of :class:`threading.Barrier`.
1435
1436 Instantiating this class may set the global start method. See
1437 :ref:`global-start-method` for more details.
1438
1439 .. versionadded:: 3.3
1440
1441 .. class:: BoundedSemaphore([value])
1442
1443 A bounded semaphore object: a close analog of
1444 :class:`threading.BoundedSemaphore`.
1445
1446 Instantiating this class may set the global start method. See
1447 :ref:`global-start-method` for more details.
1448
1449 A solitary difference from its close analog exists: its ``acquire`` method's
1450 first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
1451
1452 .. method:: locked()
1453
1454 Return a boolean indicating whether this object is locked right now.
1455
1456 .. versionadded:: 3.14
1457
1458 .. note::
1459 On macOS, this is indistinguishable from :class:`Semaphore` because
1460 ``sem_getvalue()`` is not implemented on that platform.
1461
1462 .. class:: Condition([lock])
1463
1464 A condition variable: an alias for :class:`threading.Condition`.
1465
1466 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
1467 object from :mod:`!multiprocessing`.
1468
1469 Instantiating this class may set the global start method. See
1470 :ref:`global-start-method` for more details.
1471
1472 .. versionchanged:: 3.3
1473 The :meth:`~threading.Condition.wait_for` method was added.
1474
1475 .. class:: Event()
1476
1477 A clone of :class:`threading.Event`.
1478
1479 Instantiating this class may set the global start method. See
1480 :ref:`global-start-method` for more details.
1481
1482 .. class:: Lock()
1483
1484 A non-recursive lock object: a close analog of :class:`threading.Lock`.
1485 Once a process or thread has acquired a lock, subsequent attempts to
1486 acquire it from any process or thread will block until it is released;
1487 any process or thread may release it. The concepts and behaviors of
1488 :class:`threading.Lock` as it applies to threads are replicated here in
1489 :class:`multiprocessing.Lock` as it applies to either processes or threads,
1490 except as noted.
1491
1492 Note that :class:`Lock` is actually a factory function which returns an
1493 instance of ``multiprocessing.synchronize.Lock`` initialized with a
1494 default context.
1495
1496 Instantiating this class may set the global start method. See
1497 :ref:`global-start-method` for more details.
1498
1499 :class:`Lock` supports the :term:`context manager` protocol and thus may be
1500 used in :keyword:`with` statements.
1501
1502 .. method:: acquire(block=True, timeout=None)
1503
1504 Acquire a lock, blocking or non-blocking.
1505
1506 With the *block* argument set to ``True`` (the default), the method call
1507 will block until the lock is in an unlocked state, then set it to locked
1508 and return ``True``. Note that the name of this first argument differs
1509 from that in :meth:`threading.Lock.acquire`.
1510
1511 With the *block* argument set to ``False``, the method call does not
1512 block. If the lock is currently in a locked state, return ``False``;
1513 otherwise set the lock to a locked state and return ``True``.
1514
1515 When invoked with a positive, floating-point value for *timeout*, block
1516 for at most the number of seconds specified by *timeout* as long as
1517 the lock can not be acquired. Invocations with a negative value for
1518 *timeout* are equivalent to a *timeout* of zero. Invocations with a
1519 *timeout* value of ``None`` (the default) set the timeout period to
1520 infinite. Note that the treatment of negative or ``None`` values for
1521 *timeout* differs from the implemented behavior in
1522 :meth:`threading.Lock.acquire`. The *timeout* argument has no practical
1523 implications if the *block* argument is set to ``False`` and is thus
1524 ignored. Returns ``True`` if the lock has been acquired or ``False`` if
1525 the timeout period has elapsed.
1526
1527
1528 .. method:: release()
1529
1530 Release a lock. This can be called from any process or thread, not only
1531 the process or thread which originally acquired the lock.
1532
1533 Behavior is the same as in :meth:`threading.Lock.release` except that
1534 when invoked on an unlocked lock, a :exc:`ValueError` is raised.
1535
1536
1537 .. method:: locked()
1538
1539 Return a boolean indicating whether this object is locked right now.
1540
1541 .. versionadded:: 3.14
1542
1543
1544 .. class:: RLock()
1545
1546 A recursive lock object: a close analog of :class:`threading.RLock`. A
1547 recursive lock must be released by the process or thread that acquired it.
1548 Once a process or thread has acquired a recursive lock, the same process
1549 or thread may acquire it again without blocking; that process or thread
1550 must release it once for each time it has been acquired.
1551
1552 Note that :class:`RLock` is actually a factory function which returns an
1553 instance of ``multiprocessing.synchronize.RLock`` initialized with a
1554 default context.
1555
1556 Instantiating this class may set the global start method. See
1557 :ref:`global-start-method` for more details.
1558
1559 :class:`RLock` supports the :term:`context manager` protocol and thus may be
1560 used in :keyword:`with` statements.
1561
1562
1563 .. method:: acquire(block=True, timeout=None)
1564
1565 Acquire a lock, blocking or non-blocking.
1566
1567 When invoked with the *block* argument set to ``True``, block until the
1568 lock is in an unlocked state (not owned by any process or thread) unless
1569 the lock is already owned by the current process or thread. The current
1570 process or thread then takes ownership of the lock (if it does not
1571 already have ownership) and the recursion level inside the lock increments
1572 by one, resulting in a return value of ``True``. Note that there are
1573 several differences in this first argument's behavior compared to the
1574 implementation of :meth:`threading.RLock.acquire`, starting with the name
1575 of the argument itself.
1576
1577 When invoked with the *block* argument set to ``False``, do not block.
1578 If the lock has already been acquired (and thus is owned) by another
1579 process or thread, the current process or thread does not take ownership
1580 and the recursion level within the lock is not changed, resulting in
1581 a return value of ``False``. If the lock is in an unlocked state, the
1582 current process or thread takes ownership and the recursion level is
1583 incremented, resulting in a return value of ``True``.
1584
1585 Use and behaviors of the *timeout* argument are the same as in
1586 :meth:`Lock.acquire`. Note that some of these behaviors of *timeout*
1587 differ from the implemented behaviors in :meth:`threading.RLock.acquire`.
1588
1589
1590 .. method:: release()
1591
1592 Release a lock, decrementing the recursion level. If after the
1593 decrement the recursion level is zero, reset the lock to unlocked (not
1594 owned by any process or thread) and if any other processes or threads
1595 are blocked waiting for the lock to become unlocked, allow exactly one
1596 of them to proceed. If after the decrement the recursion level is still
1597 nonzero, the lock remains locked and owned by the calling process or
1598 thread.
1599
1600 Only call this method when the calling process or thread owns the lock.
1601 An :exc:`AssertionError` is raised if this method is called by a process
1602 or thread other than the owner or if the lock is in an unlocked (unowned)
1603 state. Note that the type of exception raised in this situation
1604 differs from the implemented behavior in :meth:`threading.RLock.release`.
1605
1606
1607 .. method:: locked()
1608
1609 Return a boolean indicating whether this object is locked right now.
1610
1611 .. versionadded:: 3.14
1612
1613
1614 .. class:: Semaphore([value])
1615
1616 A semaphore object: a close analog of :class:`threading.Semaphore`.
1617
1618 Instantiating this class may set the global start method. See
1619 :ref:`global-start-method` for more details.
1620
1621 A solitary difference from its close analog exists: its ``acquire`` method's
1622 first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
1623
1624
1625 .. method:: get_value()
1626
1627 Return the current value of semaphore.
1628
1629 Note that this may raise :exc:`NotImplementedError` on platforms like
1630 macOS where ``sem_getvalue()`` is not implemented.
1631
1632
1633 .. method:: locked()
1634
1635 Return a boolean indicating whether this object is locked right now.
1636
1637 .. versionadded:: 3.14
1638
1639
1640 .. note::
1641
1642 On macOS, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
1643 a timeout will emulate that function's behavior using a sleeping loop.
1644
1645 .. note::
1646
1647 Some of this package's functionality requires a functioning shared semaphore
1648 implementation on the host operating system. Without one, the
1649 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
1650 import it will result in an :exc:`ImportError`. See
1651 :issue:`3770` for additional information.
1652
1653
1654 Shared :mod:`ctypes` Objects
1655 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1656
1657 It is possible to create shared objects using shared memory which can be
1658 inherited by child processes.
1659
1660 .. function:: Value(typecode_or_type, *args, lock=True)
1661
1662 Return a :mod:`ctypes` object allocated from shared memory. By default the
1663 return value is actually a synchronized wrapper for the object. The object
1664 itself can be accessed via the *value* attribute of a :class:`Value`.
1665
1666 *typecode_or_type* determines the type of the returned object: it is either a
1667 ctypes type or a one character typecode of the kind used by the :mod:`array`
1668 module. *\*args* is passed on to the constructor for the type.
1669
1670 If *lock* is ``True`` (the default) then a new recursive lock
1671 object is created to synchronize access to the value. If *lock* is
1672 a :class:`Lock` or :class:`RLock` object then that will be used to
1673 synchronize access to the value. If *lock* is ``False`` then
1674 access to the returned object will not be automatically protected
1675 by a lock, so it will not necessarily be "process-safe".
1676
1677 Operations like ``+=`` which involve a read and write are not
1678 atomic. So if, for instance, you want to atomically increment a
1679 shared value it is insufficient to just do ::
1680
1681 counter.value += 1
1682
1683 Assuming the associated lock is recursive (which it is by default)
1684 you can instead do ::
1685
1686 with counter.get_lock():
1687 counter.value += 1
1688
1689 Note that *lock* is a keyword-only argument.
1690
1691 .. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
1692
1693 Return a ctypes array allocated from shared memory. By default the return
1694 value is actually a synchronized wrapper for the array.
1695
1696 *typecode_or_type* determines the type of the elements of the returned array:
1697 it is either a :ref:`ctypes type <ctypes-fundamental-data-types>` or a one
1698 character typecode of the kind used by the :mod:`array` module with the
1699 exception of ``'w'``, which is not supported. In addition, the ``'c'``
1700 typecode is an alias for :class:`ctypes.c_char`. If *size_or_initializer*
1701 is an integer, then it determines the length of the array, and the array
1702 will be initially zeroed. Otherwise, *size_or_initializer* is a sequence
1703 which is used to initialize the array and whose length determines the length
1704 of the array.
1705
1706 If *lock* is ``True`` (the default) then a new lock object is created to
1707 synchronize access to the value. If *lock* is a :class:`Lock` or
1708 :class:`RLock` object then that will be used to synchronize access to the
1709 value. If *lock* is ``False`` then access to the returned object will not be
1710 automatically protected by a lock, so it will not necessarily be
1711 "process-safe".
1712
1713 Note that *lock* is a keyword only argument.
1714
1715 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
1716 attributes which can both be used to store and retrieve byte strings.
1717 While *raw* allows interaction with a :class:`bytes` object the full size of
1718 the array, reading *value* will terminate after a null byte, like most
1719 programming languages handle strings.
1720
1721
1722 The :mod:`!multiprocessing.sharedctypes` module
1723 """""""""""""""""""""""""""""""""""""""""""""""
1724
1725 .. module:: multiprocessing.sharedctypes
1726 :synopsis: Allocate ctypes objects from shared memory.
1727
1728 The :mod:`!multiprocessing.sharedctypes` module provides functions for allocating
1729 :mod:`ctypes` objects from shared memory which can be inherited by child
1730 processes.
1731
1732 .. note::
1733
1734 Although it is possible to store a pointer in shared memory remember that
1735 this will refer to a location in the address space of a specific process.
1736 However, the pointer is quite likely to be invalid in the context of a second
1737 process and trying to dereference the pointer from the second process may
1738 cause a crash.
1739
1740 .. function:: RawArray(typecode_or_type, size_or_initializer)
1741
1742 Return a ctypes array allocated from shared memory.
1743
1744 *typecode_or_type* determines the type of the elements of the returned array:
1745 it is either a ctypes type or a one character typecode of the kind used by
1746 the :mod:`array` module. If *size_or_initializer* is an integer then it
1747 determines the length of the array, and the array will be initially zeroed.
1748 Otherwise *size_or_initializer* is a sequence which is used to initialize the
1749 array and whose length determines the length of the array.
1750
1751 Note that setting and getting an element is potentially non-atomic -- use
1752 :func:`Array` instead to make sure that access is automatically synchronized
1753 using a lock.
1754
1755 .. function:: RawValue(typecode_or_type, *args)
1756
1757 Return a ctypes object allocated from shared memory.
1758
1759 *typecode_or_type* determines the type of the returned object: it is either a
1760 ctypes type or a one character typecode of the kind used by the :mod:`array`
1761 module. *\*args* is passed on to the constructor for the type.
1762
1763 Note that setting and getting the value is potentially non-atomic -- use
1764 :func:`Value` instead to make sure that access is automatically synchronized
1765 using a lock.
1766
1767 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
1768 attributes which allow one to use it to store and retrieve strings -- see
1769 documentation for :mod:`ctypes`.
1770
1771 .. function:: Array(typecode_or_type, size_or_initializer, *, lock=True, ctx=None)
1772
1773 The same as :func:`RawArray` except that depending on the value of *lock* a
1774 process-safe synchronization wrapper may be returned instead of a raw ctypes
1775 array.
1776
1777 If *lock* is ``True`` (the default) then a new lock object is created to
1778 synchronize access to the value. If *lock* is a
1779 :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
1780 then that will be used to synchronize access to the
1781 value. If *lock* is ``False`` then access to the returned object will not be
1782 automatically protected by a lock, so it will not necessarily be
1783 "process-safe".
1784
1785 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1786 calling this may set the global start method. See
1787 :ref:`global-start-method` for more details.
1788
1789 Note that *lock* and *ctx* are keyword-only parameters.
1790
1791 .. function:: Value(typecode_or_type, *args, lock=True, ctx=None)
1792
1793 The same as :func:`RawValue` except that depending on the value of *lock* a
1794 process-safe synchronization wrapper may be returned instead of a raw ctypes
1795 object.
1796
1797 If *lock* is ``True`` (the default) then a new lock object is created to
1798 synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or
1799 :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
1800 value. If *lock* is ``False`` then access to the returned object will not be
1801 automatically protected by a lock, so it will not necessarily be
1802 "process-safe".
1803
1804 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1805 calling this may set the global start method. See
1806 :ref:`global-start-method` for more details.
1807
1808 Note that *lock* and *ctx* are keyword-only parameters.
1809
1810 .. function:: copy(obj)
1811
1812 Return a ctypes object allocated from shared memory which is a copy of the
1813 ctypes object *obj*.
1814
1815 .. function:: synchronized(obj, lock=None, ctx=None)
1816
1817 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1818 synchronize access. If *lock* is ``None`` (the default) then a
1819 :class:`multiprocessing.RLock` object is created automatically.
1820
1821 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1822 calling this may set the global start method. See
1823 :ref:`global-start-method` for more details.
1824
1825 A synchronized wrapper will have two methods in addition to those of the
1826 object it wraps: :meth:`get_obj` returns the wrapped object and
1827 :meth:`get_lock` returns the lock object used for synchronization.
1828
1829 Note that accessing the ctypes object through the wrapper can be a lot slower
1830 than accessing the raw ctypes object.
1831
1832 .. versionchanged:: 3.5
1833 Synchronized objects support the :term:`context manager` protocol.
1834
1835
1836 The table below compares the syntax for creating shared ctypes objects from
1837 shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1838 subclass of :class:`ctypes.Structure`.)
1839
1840 ==================== ========================== ===========================
1841 ctypes sharedctypes using type sharedctypes using typecode
1842 ==================== ========================== ===========================
1843 c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1844 MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1845 (c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1846 (c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1847 ==================== ========================== ===========================
1848
1849
1850 Below is an example where a number of ctypes objects are modified by a child
1851 process::
1852
1853 from multiprocessing import Process, Lock
1854 from multiprocessing.sharedctypes import Value, Array
1855 from ctypes import Structure, c_double
1856
1857 class Point(Structure):
1858 _fields_ = [('x', c_double), ('y', c_double)]
1859
1860 def modify(n, x, s, A):
1861 n.value **= 2
1862 x.value **= 2
1863 s.value = s.value.upper()
1864 for a in A:
1865 a.x **= 2
1866 a.y **= 2
1867
1868 if __name__ == '__main__':
1869 lock = Lock()
1870
1871 n = Value('i', 7)
1872 x = Value(c_double, 1.0/3.0, lock=False)
1873 s = Array('c', b'hello world', lock=lock)
1874 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1875
1876 p = Process(target=modify, args=(n, x, s, A))
1877 p.start()
1878 p.join()
1879
1880 print(n.value)
1881 print(x.value)
1882 print(s.value)
1883 print([(a.x, a.y) for a in A])
1884
1885
1886 .. highlight:: none
1887
1888 The results printed are ::
1889
1890 49
1891 0.1111111111111111
1892 HELLO WORLD
1893 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1894
1895 .. highlight:: python3
1896
1897
1898 .. _multiprocessing-managers:
1899
1900 Managers
1901 ^^^^^^^^
1902
1903 Managers provide a way to create data which can be shared between different
1904 processes, including sharing over a network between processes running on
1905 different machines. A manager object controls a server process which manages
1906 *shared objects*. Other processes can access the shared objects by using
1907 proxies.
1908
1909 .. function:: multiprocessing.Manager()
1910 :module:
1911
1912 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1913 can be used for sharing objects between processes. The returned manager
1914 object corresponds to a spawned child process and has methods which will
1915 create shared objects and return corresponding proxies.
1916
1917 .. module:: multiprocessing.managers
1918 :synopsis: Share data between process with shared objects.
1919
1920 Manager processes will be shutdown as soon as they are garbage collected or
1921 their parent process exits. The manager classes are defined in the
1922 :mod:`multiprocessing.managers` module:
1923
1924 .. class:: BaseManager(address=None, authkey=None, serializer='pickle', ctx=None, *, shutdown_timeout=1.0)
1925
1926 Create a BaseManager object.
1927
1928 Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
1929 that the manager object refers to a started manager process.
1930
1931 *address* is the address on which the manager process listens for new
1932 connections. If *address* is ``None`` then an arbitrary one is chosen.
1933
1934 *authkey* is the authentication key which will be used to check the
1935 validity of incoming connections to the server process. If
1936 *authkey* is ``None`` then ``current_process().authkey`` is used.
1937 Otherwise *authkey* is used and it must be a byte string.
1938
1939 *serializer* must be ``'pickle'`` (use :mod:`pickle` serialization) or
1940 ``'xmlrpclib'`` (use :mod:`xmlrpc.client` serialization).
1941
1942 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1943 calling this may set the global start method. See
1944 :ref:`global-start-method` for more details.
1945
1946 *shutdown_timeout* is a timeout in seconds used to wait until the process
1947 used by the manager completes in the :meth:`shutdown` method. If the
1948 shutdown times out, the process is terminated. If terminating the process
1949 also times out, the process is killed.
1950
1951 .. versionchanged:: 3.11
1952 Added the *shutdown_timeout* parameter.
1953
1954 .. method:: start([initializer[, initargs]])
1955
1956 Start a subprocess to start the manager. If *initializer* is not ``None``
1957 then the subprocess will call ``initializer(*initargs)`` when it starts.
1958
1959 .. method:: get_server()
1960
1961 Returns a :class:`Server` object which represents the actual server under
1962 the control of the Manager. The :class:`Server` object supports the
1963 :meth:`serve_forever` method::
1964
1965 >>> from multiprocessing.managers import BaseManager
1966 >>> manager = BaseManager(address=('', 50000), authkey=b'abc')
1967 >>> server = manager.get_server()
1968 >>> server.serve_forever()
1969
1970 :class:`Server` additionally has an :attr:`address` attribute.
1971
1972 .. method:: connect()
1973
1974 Connect a local manager object to a remote manager process::
1975
1976 >>> from multiprocessing.managers import BaseManager
1977 >>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
1978 >>> m.connect()
1979
1980 .. method:: shutdown()
1981
1982 Stop the process used by the manager. This is only available if
1983 :meth:`start` has been used to start the server process.
1984
1985 This can be called multiple times.
1986
1987 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1988
1989 A classmethod which can be used for registering a type or callable with
1990 the manager class.
1991
1992 *typeid* is a "type identifier" which is used to identify a particular
1993 type of shared object. This must be a string.
1994
1995 *callable* is a callable used for creating objects for this type
1996 identifier. If a manager instance will be connected to the
1997 server using the :meth:`connect` method, or if the
1998 *create_method* argument is ``False`` then this can be left as
1999 ``None``.
2000
2001 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
2002 proxies for shared objects with this *typeid*. If ``None`` then a proxy
2003 class is created automatically.
2004
2005 *exposed* is used to specify a sequence of method names which proxies for
2006 this typeid should be allowed to access using
2007 :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then
2008 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
2009 where no exposed list is specified, all "public methods" of the shared
2010 object will be accessible. (Here a "public method" means any attribute
2011 which has a :meth:`~object.__call__` method and whose name does not begin
2012 with ``'_'``.)
2013
2014 *method_to_typeid* is a mapping used to specify the return type of those
2015 exposed methods which should return a proxy. It maps method names to
2016 typeid strings. (If *method_to_typeid* is ``None`` then
2017 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
2018 method's name is not a key of this mapping or if the mapping is ``None``
2019 then the object returned by the method will be copied by value.
2020
2021 *create_method* determines whether a method should be created with name
2022 *typeid* which can be used to tell the server process to create a new
2023 shared object and return a proxy for it. By default it is ``True``.
2024
2025 :class:`BaseManager` instances also have one read-only property:
2026
2027 .. attribute:: address
2028
2029 The address used by the manager.
2030
2031 .. versionchanged:: 3.3
2032 Manager objects support the context management protocol -- see
2033 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` starts the
2034 server process (if it has not already started) and then returns the
2035 manager object. :meth:`~contextmanager.__exit__` calls :meth:`shutdown`.
2036
2037 In previous versions :meth:`~contextmanager.__enter__` did not start the
2038 manager's server process if it was not already started.
2039
2040 .. class:: SyncManager
2041
2042 A subclass of :class:`BaseManager` which can be used for the synchronization
2043 of processes. Objects of this type are returned by
2044 :func:`multiprocessing.Manager`.
2045
2046 Its methods create and return :ref:`multiprocessing-proxy_objects` for a
2047 number of commonly used data types to be synchronized across processes.
2048 This notably includes shared lists and dictionaries.
2049
2050 .. method:: Barrier(parties[, action[, timeout]])
2051
2052 Create a shared :class:`threading.Barrier` object and return a
2053 proxy for it.
2054
2055 .. versionadded:: 3.3
2056
2057 .. method:: BoundedSemaphore([value])
2058
2059 Create a shared :class:`threading.BoundedSemaphore` object and return a
2060 proxy for it.
2061
2062 .. method:: Condition([lock])
2063
2064 Create a shared :class:`threading.Condition` object and return a proxy for
2065 it.
2066
2067 If *lock* is supplied then it should be a proxy for a
2068 :class:`threading.Lock` or :class:`threading.RLock` object.
2069
2070 .. versionchanged:: 3.3
2071 The :meth:`~threading.Condition.wait_for` method was added.
2072
2073 .. method:: Event()
2074
2075 Create a shared :class:`threading.Event` object and return a proxy for it.
2076
2077 .. method:: Lock()
2078
2079 Create a shared :class:`threading.Lock` object and return a proxy for it.
2080
2081 .. method:: Namespace()
2082
2083 Create a shared :class:`Namespace` object and return a proxy for it.
2084
2085 .. method:: Queue([maxsize])
2086
2087 Create a shared :class:`queue.Queue` object and return a proxy for it.
2088
2089 .. method:: RLock()
2090
2091 Create a shared :class:`threading.RLock` object and return a proxy for it.
2092
2093 .. method:: Semaphore([value])
2094
2095 Create a shared :class:`threading.Semaphore` object and return a proxy for
2096 it.
2097
2098 .. method:: Array(typecode, sequence)
2099
2100 Create an array and return a proxy for it.
2101
2102 .. method:: Value(typecode, value)
2103
2104 Create an object with a writable ``value`` attribute and return a proxy
2105 for it.
2106
2107 .. method:: dict()
2108 dict(mapping)
2109 dict(sequence)
2110
2111 Create a shared :class:`dict` object and return a proxy for it.
2112
2113 .. method:: list()
2114 list(sequence)
2115
2116 Create a shared :class:`list` object and return a proxy for it.
2117
2118 .. method:: set()
2119 set(sequence)
2120 set(mapping)
2121
2122 Create a shared :class:`set` object and return a proxy for it.
2123
2124 .. versionadded:: 3.14
2125 :class:`set` support was added.
2126
2127 .. versionchanged:: 3.6
2128 Shared objects are capable of being nested. For example, a shared
2129 container object such as a shared list can contain other shared objects
2130 which will all be managed and synchronized by the :class:`SyncManager`.
2131
2132 .. class:: Namespace
2133
2134 A type that can register with :class:`SyncManager`.
2135
2136 A namespace object has no public methods, but does have writable attributes.
2137 Its representation shows the values of its attributes.
2138
2139 However, when using a proxy for a namespace object, an attribute beginning
2140 with ``'_'`` will be an attribute of the proxy and not an attribute of the
2141 referent:
2142
2143 .. doctest::
2144
2145 >>> mp_context = multiprocessing.get_context('spawn')
2146 >>> manager = mp_context.Manager()
2147 >>> Global = manager.Namespace()
2148 >>> Global.x = 10
2149 >>> Global.y = 'hello'
2150 >>> Global._z = 12.3 # this is an attribute of the proxy
2151 >>> print(Global)
2152 Namespace(x=10, y='hello')
2153
2154
2155 Customized managers
2156 """""""""""""""""""
2157
2158 To create one's own manager, one creates a subclass of :class:`BaseManager` and
2159 uses the :meth:`~BaseManager.register` classmethod to register new types or
2160 callables with the manager class. For example::
2161
2162 from multiprocessing.managers import BaseManager
2163
2164 class MathsClass:
2165 def add(self, x, y):
2166 return x + y
2167 def mul(self, x, y):
2168 return x * y
2169
2170 class MyManager(BaseManager):
2171 pass
2172
2173 MyManager.register('Maths', MathsClass)
2174
2175 if __name__ == '__main__':
2176 with MyManager() as manager:
2177 maths = manager.Maths()
2178 print(maths.add(4, 3)) # prints 7
2179 print(maths.mul(7, 8)) # prints 56
2180
2181
2182 Using a remote manager
2183 """"""""""""""""""""""
2184
2185 It is possible to run a manager server on one machine and have clients use it
2186 from other machines (assuming that the firewalls involved allow it).
2187
2188 Running the following commands creates a server for a single shared queue which
2189 remote clients can access::
2190
2191 >>> from multiprocessing.managers import BaseManager
2192 >>> from queue import Queue
2193 >>> queue = Queue()
2194 >>> class QueueManager(BaseManager): pass
2195 >>> QueueManager.register('get_queue', callable=lambda:queue)
2196 >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
2197 >>> s = m.get_server()
2198 >>> s.serve_forever()
2199
2200 One client can access the server as follows::
2201
2202 >>> from multiprocessing.managers import BaseManager
2203 >>> class QueueManager(BaseManager): pass
2204 >>> QueueManager.register('get_queue')
2205 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
2206 >>> m.connect()
2207 >>> queue = m.get_queue()
2208 >>> queue.put('hello')
2209
2210 Another client can also use it::
2211
2212 >>> from multiprocessing.managers import BaseManager
2213 >>> class QueueManager(BaseManager): pass
2214 >>> QueueManager.register('get_queue')
2215 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
2216 >>> m.connect()
2217 >>> queue = m.get_queue()
2218 >>> queue.get()
2219 'hello'
2220
2221 Local processes can also access that queue, using the code from above on the
2222 client to access it remotely::
2223
2224 >>> from multiprocessing import Process, Queue
2225 >>> from multiprocessing.managers import BaseManager
2226 >>> class Worker(Process):
2227 ... def __init__(self, q):
2228 ... self.q = q
2229 ... super().__init__()
2230 ... def run(self):
2231 ... self.q.put('local hello')
2232 ...
2233 >>> queue = Queue()
2234 >>> w = Worker(queue)
2235 >>> w.start()
2236 >>> class QueueManager(BaseManager): pass
2237 ...
2238 >>> QueueManager.register('get_queue', callable=lambda: queue)
2239 >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
2240 >>> s = m.get_server()
2241 >>> s.serve_forever()
2242
2243 .. _multiprocessing-proxy_objects:
2244
2245 Proxy Objects
2246 ^^^^^^^^^^^^^
2247
2248 A proxy is an object which *refers* to a shared object which lives (presumably)
2249 in a different process. The shared object is said to be the *referent* of the
2250 proxy. Multiple proxy objects may have the same referent.
2251
2252 A proxy object has methods which invoke corresponding methods of its referent
2253 (although not every method of the referent will necessarily be available through
2254 the proxy). In this way, a proxy can be used just like its referent can:
2255
2256 .. doctest::
2257
2258 >>> mp_context = multiprocessing.get_context('spawn')
2259 >>> manager = mp_context.Manager()
2260 >>> l = manager.list([i*i for i in range(10)])
2261 >>> print(l)
2262 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2263 >>> print(repr(l))
2264 <ListProxy object, typeid 'list' at 0x...>
2265 >>> l[4]
2266 16
2267 >>> l[2:5]
2268 [4, 9, 16]
2269
2270 Notice that applying :func:`str` to a proxy will return the representation of
2271 the referent, whereas applying :func:`repr` will return the representation of
2272 the proxy.
2273
2274 An important feature of proxy objects is that they are picklable so they can be
2275 passed between processes. As such, a referent can contain
2276 :ref:`multiprocessing-proxy_objects`. This permits nesting of these managed
2277 lists, dicts, and other :ref:`multiprocessing-proxy_objects`:
2278
2279 .. doctest::
2280
2281 >>> a = manager.list()
2282 >>> b = manager.list()
2283 >>> a.append(b) # referent of a now contains referent of b
2284 >>> print(a, b)
2285 [<ListProxy object, typeid 'list' at ...>] []
2286 >>> b.append('hello')
2287 >>> print(a[0], b)
2288 ['hello'] ['hello']
2289
2290 Similarly, dict and list proxies may be nested inside one another::
2291
2292 >>> l_outer = manager.list([ manager.dict() for i in range(2) ])
2293 >>> d_first_inner = l_outer[0]
2294 >>> d_first_inner['a'] = 1
2295 >>> d_first_inner['b'] = 2
2296 >>> l_outer[1]['c'] = 3
2297 >>> l_outer[1]['z'] = 26
2298 >>> print(l_outer[0])
2299 {'a': 1, 'b': 2}
2300 >>> print(l_outer[1])
2301 {'c': 3, 'z': 26}
2302
2303 If standard (non-proxy) :class:`list` or :class:`dict` objects are contained
2304 in a referent, modifications to those mutable values will not be propagated
2305 through the manager because the proxy has no way of knowing when the values
2306 contained within are modified. However, storing a value in a container proxy
2307 (which triggers a ``__setitem__`` on the proxy object) does propagate through
2308 the manager and so to effectively modify such an item, one could re-assign the
2309 modified value to the container proxy::
2310
2311 # create a list proxy and append a mutable object (a dictionary)
2312 lproxy = manager.list()
2313 lproxy.append({})
2314 # now mutate the dictionary
2315 d = lproxy[0]
2316 d['a'] = 1
2317 d['b'] = 2
2318 # at this point, the changes to d are not yet synced, but by
2319 # updating the dictionary, the proxy is notified of the change
2320 lproxy[0] = d
2321
2322 This approach is perhaps less convenient than employing nested
2323 :ref:`multiprocessing-proxy_objects` for most use cases but also
2324 demonstrates a level of control over the synchronization.
2325
2326 .. note::
2327
2328 The proxy types in :mod:`!multiprocessing` do nothing to support comparisons
2329 by value. So, for instance, we have:
2330
2331 .. doctest::
2332
2333 >>> manager.list([1,2,3]) == [1,2,3]
2334 False
2335
2336 One should just use a copy of the referent instead when making comparisons.
2337
2338 .. class:: BaseProxy
2339
2340 Proxy objects are instances of subclasses of :class:`BaseProxy`.
2341
2342 .. method:: _callmethod(methodname[, args[, kwds]])
2343
2344 Call and return the result of a method of the proxy's referent.
2345
2346 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
2347
2348 proxy._callmethod(methodname, args, kwds)
2349
2350 will evaluate the expression ::
2351
2352 getattr(obj, methodname)(*args, **kwds)
2353
2354 in the manager's process.
2355
2356 The returned value will be a copy of the result of the call or a proxy to
2357 a new shared object -- see documentation for the *method_to_typeid*
2358 argument of :meth:`BaseManager.register`.
2359
2360 If an exception is raised by the call, then is re-raised by
2361 :meth:`_callmethod`. If some other exception is raised in the manager's
2362 process then this is converted into a :exc:`RemoteError` exception and is
2363 raised by :meth:`_callmethod`.
2364
2365 Note in particular that an exception will be raised if *methodname* has
2366 not been *exposed*.
2367
2368 An example of the usage of :meth:`_callmethod`:
2369
2370 .. doctest::
2371
2372 >>> l = manager.list(range(10))
2373 >>> l._callmethod('__len__')
2374 10
2375 >>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
2376 [2, 3, 4, 5, 6]
2377 >>> l._callmethod('__getitem__', (20,)) # equivalent to l[20]
2378 Traceback (most recent call last):
2379 ...
2380 IndexError: list index out of range
2381
2382 .. method:: _getvalue()
2383
2384 Return a copy of the referent.
2385
2386 If the referent is unpicklable then this will raise an exception.
2387
2388 .. method:: __repr__
2389
2390 Return a representation of the proxy object.
2391
2392 .. method:: __str__
2393
2394 Return the representation of the referent.
2395
2396
2397 Cleanup
2398 """""""
2399
2400 A proxy object uses a weakref callback so that when it gets garbage collected it
2401 deregisters itself from the manager which owns its referent.
2402
2403 A shared object gets deleted from the manager process when there are no longer
2404 any proxies referring to it.
2405
2406
2407 Process Pools
2408 ^^^^^^^^^^^^^
2409
2410 .. module:: multiprocessing.pool
2411 :synopsis: Create pools of processes.
2412
2413 One can create a pool of processes which will carry out tasks submitted to it
2414 with the :class:`Pool` class.
2415
2416 .. class:: Pool([processes[, initializer[, initargs[, maxtasksperchild [, context]]]]])
2417
2418 A process pool object which controls a pool of worker processes to which jobs
2419 can be submitted. It supports asynchronous results with timeouts and
2420 callbacks and has a parallel map implementation.
2421
2422 *processes* is the number of worker processes to use. If *processes* is
2423 ``None`` then the number returned by :func:`os.process_cpu_count` is used.
2424
2425 If *initializer* is not ``None`` then each worker process will call
2426 ``initializer(*initargs)`` when it starts.
2427
2428 *maxtasksperchild* is the number of tasks a worker process can complete
2429 before it will exit and be replaced with a fresh worker process, to enable
2430 unused resources to be freed. The default *maxtasksperchild* is ``None``, which
2431 means worker processes will live as long as the pool.
2432
2433 *context* can be used to specify the context used for starting
2434 the worker processes. Usually a pool is created using the
2435 function :func:`multiprocessing.Pool` or the :meth:`Pool` method
2436 of a context object. In both cases *context* is set
2437 appropriately. If ``None``, calling this function will have the side effect
2438 of setting the current global start method if it has not been set already.
2439 See the :func:`get_context` function.
2440
2441 Note that the methods of the pool object should only be called by
2442 the process which created the pool.
2443
2444 .. warning::
2445 :class:`multiprocessing.pool` objects have internal resources that need to be
2446 properly managed (like any other resource) by using the pool as a context manager
2447 or by calling :meth:`close` and :meth:`terminate` manually. Failure to do this
2448 can lead to the process hanging on finalization.
2449
2450 Note that it is **not correct** to rely on the garbage collector to destroy the pool
2451 as CPython does not assure that the finalizer of the pool will be called
2452 (see :meth:`object.__del__` for more information).
2453
2454 .. versionchanged:: 3.2
2455 Added the *maxtasksperchild* parameter.
2456
2457 .. versionchanged:: 3.4
2458 Added the *context* parameter.
2459
2460 .. versionchanged:: 3.13
2461 *processes* uses :func:`os.process_cpu_count` by default, instead of
2462 :func:`os.cpu_count`.
2463
2464 .. note::
2465
2466 Worker processes within a :class:`Pool` typically live for the complete
2467 duration of the Pool's work queue. A frequent pattern found in other
2468 systems (such as Apache, mod_wsgi, etc) to free resources held by
2469 workers is to allow a worker within a pool to complete only a set
2470 amount of work before exiting, being cleaned up and a new
2471 process spawned to replace the old one. The *maxtasksperchild*
2472 argument to the :class:`Pool` exposes this ability to the end user.
2473
2474 .. method:: apply(func[, args[, kwds]])
2475
2476 Call *func* with arguments *args* and keyword arguments *kwds*. It blocks
2477 until the result is ready. Given this blocks, :meth:`apply_async` is
2478 better suited for performing work in parallel. Additionally, *func*
2479 is only executed in one of the workers of the pool.
2480
2481 .. method:: apply_async(func[, args[, kwds[, callback[, error_callback]]]])
2482
2483 A variant of the :meth:`apply` method which returns a
2484 :class:`~multiprocessing.pool.AsyncResult` object.
2485
2486 If *callback* is specified then it should be a callable which accepts a
2487 single argument. When the result becomes ready *callback* is applied to
2488 it, that is unless the call failed, in which case the *error_callback*
2489 is applied instead.
2490
2491 If *error_callback* is specified then it should be a callable which
2492 accepts a single argument. If the target function fails, then
2493 the *error_callback* is called with the exception instance.
2494
2495 Callbacks should complete immediately since otherwise the thread which
2496 handles the results will get blocked.
2497
2498 .. method:: map(func, iterable[, chunksize])
2499
2500 A parallel equivalent of the :func:`map` built-in function (it supports only
2501 one *iterable* argument though, for multiple iterables see :meth:`starmap`).
2502 It blocks until the result is ready.
2503
2504 This method chops the iterable into a number of chunks which it submits to
2505 the process pool as separate tasks. The (approximate) size of these
2506 chunks can be specified by setting *chunksize* to a positive integer.
2507
2508 Note that it may cause high memory usage for very long iterables. Consider
2509 using :meth:`imap` or :meth:`imap_unordered` with explicit *chunksize*
2510 option for better efficiency.
2511
2512 .. method:: map_async(func, iterable[, chunksize[, callback[, error_callback]]])
2513
2514 A variant of the :meth:`.map` method which returns a
2515 :class:`~multiprocessing.pool.AsyncResult` object.
2516
2517 If *callback* is specified then it should be a callable which accepts a
2518 single argument. When the result becomes ready *callback* is applied to
2519 it, that is unless the call failed, in which case the *error_callback*
2520 is applied instead.
2521
2522 If *error_callback* is specified then it should be a callable which
2523 accepts a single argument. If the target function fails, then
2524 the *error_callback* is called with the exception instance.
2525
2526 Callbacks should complete immediately since otherwise the thread which
2527 handles the results will get blocked.
2528
2529 .. method:: imap(func, iterable[, chunksize])
2530
2531 A lazier version of :meth:`.map`.
2532
2533 The *chunksize* argument is the same as the one used by the :meth:`.map`
2534 method. For very long iterables using a large value for *chunksize* can
2535 make the job complete **much** faster than using the default value of
2536 ``1``.
2537
2538 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
2539 returned by the :meth:`imap` method has an optional *timeout* parameter:
2540 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
2541 result cannot be returned within *timeout* seconds.
2542
2543 .. method:: imap_unordered(func, iterable[, chunksize])
2544
2545 The same as :meth:`imap` except that the ordering of the results from the
2546 returned iterator should be considered arbitrary. (Only when there is
2547 only one worker process is the order guaranteed to be "correct".)
2548
2549 .. method:: starmap(func, iterable[, chunksize])
2550
2551 Like :meth:`~multiprocessing.pool.Pool.map` except that the
2552 elements of the *iterable* are expected to be iterables that are
2553 unpacked as arguments.
2554
2555 Hence an *iterable* of ``[(1,2), (3, 4)]`` results in ``[func(1,2),
2556 func(3,4)]``.
2557
2558 .. versionadded:: 3.3
2559
2560 .. method:: starmap_async(func, iterable[, chunksize[, callback[, error_callback]]])
2561
2562 A combination of :meth:`starmap` and :meth:`map_async` that iterates over
2563 *iterable* of iterables and calls *func* with the iterables unpacked.
2564 Returns a result object.
2565
2566 .. versionadded:: 3.3
2567
2568 .. method:: close()
2569
2570 Prevents any more tasks from being submitted to the pool. Once all the
2571 tasks have been completed the worker processes will exit.
2572
2573 .. method:: terminate()
2574
2575 Stops the worker processes immediately without completing outstanding
2576 work. When the pool object is garbage collected :meth:`terminate` will be
2577 called immediately.
2578
2579 .. method:: join()
2580
2581 Wait for the worker processes to exit. One must call :meth:`close` or
2582 :meth:`terminate` before using :meth:`join`.
2583
2584 .. versionchanged:: 3.3
2585 Pool objects now support the context management protocol -- see
2586 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the
2587 pool object, and :meth:`~contextmanager.__exit__` calls :meth:`terminate`.
2588
2589
2590 .. class:: AsyncResult
2591
2592 The class of the result returned by :meth:`Pool.apply_async` and
2593 :meth:`Pool.map_async`.
2594
2595 .. method:: get([timeout])
2596
2597 Return the result when it arrives. If *timeout* is not ``None`` and the
2598 result does not arrive within *timeout* seconds then
2599 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
2600 an exception then that exception will be reraised by :meth:`get`.
2601
2602 .. method:: wait([timeout])
2603
2604 Wait until the result is available or until *timeout* seconds pass.
2605
2606 .. method:: ready()
2607
2608 Return whether the call has completed.
2609
2610 .. method:: successful()
2611
2612 Return whether the call completed without raising an exception. Will
2613 raise :exc:`ValueError` if the result is not ready.
2614
2615 .. versionchanged:: 3.7
2616 If the result is not ready, :exc:`ValueError` is raised instead of
2617 :exc:`AssertionError`.
2618
2619 The following example demonstrates the use of a pool::
2620
2621 from multiprocessing import Pool
2622 import time
2623
2624 def f(x):
2625 return x*x
2626
2627 if __name__ == '__main__':
2628 with Pool(processes=4) as pool: # start 4 worker processes
2629 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
2630 print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow
2631
2632 print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]"
2633
2634 it = pool.imap(f, range(10))
2635 print(next(it)) # prints "0"
2636 print(next(it)) # prints "1"
2637 print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow
2638
2639 result = pool.apply_async(time.sleep, (10,))
2640 print(result.get(timeout=1)) # raises multiprocessing.TimeoutError
2641
2642
2643 .. _multiprocessing-listeners-clients:
2644
2645 Listeners and Clients
2646 ^^^^^^^^^^^^^^^^^^^^^
2647
2648 .. module:: multiprocessing.connection
2649 :synopsis: API for dealing with sockets.
2650
2651 Usually message passing between processes is done using queues or by using
2652 :class:`~Connection` objects returned by
2653 :func:`~multiprocessing.Pipe`.
2654
2655 However, the :mod:`!multiprocessing.connection` module allows some extra
2656 flexibility. It basically gives a high level message oriented API for dealing
2657 with sockets or Windows named pipes. It also has support for *digest
2658 authentication* using the :mod:`hmac` module, and for polling
2659 multiple connections at the same time.
2660
2661
2662 .. function:: deliver_challenge(connection, authkey)
2663
2664 Send a randomly generated message to the other end of the connection and wait
2665 for a reply.
2666
2667 If the reply matches the digest of the message using *authkey* as the key
2668 then a welcome message is sent to the other end of the connection. Otherwise
2669 :exc:`~multiprocessing.AuthenticationError` is raised.
2670
2671 .. function:: answer_challenge(connection, authkey)
2672
2673 Receive a message, calculate the digest of the message using *authkey* as the
2674 key, and then send the digest back.
2675
2676 If a welcome message is not received, then
2677 :exc:`~multiprocessing.AuthenticationError` is raised.
2678
2679 .. function:: Client(address[, family[, authkey]])
2680
2681 Attempt to set up a connection to the listener which is using address
2682 *address*, returning a :class:`~Connection`.
2683
2684 The type of the connection is determined by *family* argument, but this can
2685 generally be omitted since it can usually be inferred from the format of
2686 *address*. (See :ref:`multiprocessing-address-formats`)
2687
2688 If *authkey* is given and not ``None``, it should be a byte string and will be
2689 used as the secret key for an HMAC-based authentication challenge. No
2690 authentication is done if *authkey* is ``None``.
2691 :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails.
2692 See :ref:`multiprocessing-auth-keys`.
2693
2694 .. class:: Listener([address[, family[, backlog[, authkey]]]])
2695
2696 A wrapper for a bound socket or Windows named pipe which is 'listening' for
2697 connections.
2698
2699 *address* is the address to be used by the bound socket or named pipe of the
2700 listener object.
2701
2702 .. note::
2703
2704 If an address of '0.0.0.0' is used, the address will not be a connectable
2705 end point on Windows. If you require a connectable end-point,
2706 you should use '127.0.0.1'.
2707
2708 *family* is the type of socket (or named pipe) to use. This can be one of
2709 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
2710 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
2711 the first is guaranteed to be available. If *family* is ``None`` then the
2712 family is inferred from the format of *address*. If *address* is also
2713 ``None`` then a default is chosen. This default is the family which is
2714 assumed to be the fastest available. See
2715 :ref:`multiprocessing-address-formats`. Note that if *family* is
2716 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
2717 private temporary directory created using :func:`tempfile.mkstemp`.
2718
2719 If the listener object uses a socket then *backlog* (1 by default) is passed
2720 to the :meth:`~socket.socket.listen` method of the socket once it has been
2721 bound.
2722
2723 If *authkey* is given and not ``None``, it should be a byte string and will be
2724 used as the secret key for an HMAC-based authentication challenge. No
2725 authentication is done if *authkey* is ``None``.
2726 :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails.
2727 See :ref:`multiprocessing-auth-keys`.
2728
2729 .. method:: accept()
2730
2731 Accept a connection on the bound socket or named pipe of the listener
2732 object and return a :class:`~Connection` object.
2733 If authentication is attempted and fails, then
2734 :exc:`~multiprocessing.AuthenticationError` is raised.
2735
2736 .. method:: close()
2737
2738 Close the bound socket or named pipe of the listener object. This is
2739 called automatically when the listener is garbage collected. However it
2740 is advisable to call it explicitly.
2741
2742 Listener objects have the following read-only properties:
2743
2744 .. attribute:: address
2745
2746 The address which is being used by the Listener object.
2747
2748 .. attribute:: last_accepted
2749
2750 The address from which the last accepted connection came. If this is
2751 unavailable then it is ``None``.
2752
2753 .. versionchanged:: 3.3
2754 Listener objects now support the context management protocol -- see
2755 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the
2756 listener object, and :meth:`~contextmanager.__exit__` calls :meth:`close`.
2757
2758 .. function:: wait(object_list, timeout=None)
2759
2760 Wait till an object in *object_list* is ready. Returns the list of
2761 those objects in *object_list* which are ready. If *timeout* is a
2762 float then the call blocks for at most that many seconds. If
2763 *timeout* is ``None`` then it will block for an unlimited period.
2764 A negative timeout is equivalent to a zero timeout.
2765
2766 For both POSIX and Windows, an object can appear in *object_list* if
2767 it is
2768
2769 * a readable :class:`~multiprocessing.connection.Connection` object;
2770 * a connected and readable :class:`socket.socket` object; or
2771 * the :attr:`~multiprocessing.Process.sentinel` attribute of a
2772 :class:`~multiprocessing.Process` object.
2773
2774 A connection or socket object is ready when there is data available
2775 to be read from it, or the other end has been closed.
2776
2777 **POSIX**: ``wait(object_list, timeout)`` almost equivalent
2778 ``select.select(object_list, [], [], timeout)``. The difference is
2779 that, if :func:`select.select` is interrupted by a signal, it can
2780 raise :exc:`OSError` with an error number of ``EINTR``, whereas
2781 :func:`wait` will not.
2782
2783 **Windows**: An item in *object_list* must either be an integer
2784 handle which is waitable (according to the definition used by the
2785 documentation of the Win32 function ``WaitForMultipleObjects()``)
2786 or it can be an object with a :meth:`~io.IOBase.fileno` method which returns a
2787 socket handle or pipe handle. (Note that pipe handles and socket
2788 handles are **not** waitable handles.)
2789
2790 .. versionadded:: 3.3
2791
2792
2793 **Examples**
2794
2795 The following server code creates a listener which uses ``'secret password'`` as
2796 an authentication key. It then waits for a connection and sends some data to
2797 the client::
2798
2799 from multiprocessing.connection import Listener
2800 from array import array
2801
2802 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
2803
2804 with Listener(address, authkey=b'secret password') as listener:
2805 with listener.accept() as conn:
2806 print('connection accepted from', listener.last_accepted)
2807
2808 conn.send([2.25, None, 'junk', float])
2809
2810 conn.send_bytes(b'hello')
2811
2812 conn.send_bytes(array('i', [42, 1729]))
2813
2814 The following code connects to the server and receives some data from the
2815 server::
2816
2817 from multiprocessing.connection import Client
2818 from array import array
2819
2820 address = ('localhost', 6000)
2821
2822 with Client(address, authkey=b'secret password') as conn:
2823 print(conn.recv()) # => [2.25, None, 'junk', float]
2824
2825 print(conn.recv_bytes()) # => 'hello'
2826
2827 arr = array('i', [0, 0, 0, 0, 0])
2828 print(conn.recv_bytes_into(arr)) # => 8
2829 print(arr) # => array('i', [42, 1729, 0, 0, 0])
2830
2831 The following code uses :func:`~multiprocessing.connection.wait` to
2832 wait for messages from multiple processes at once::
2833
2834 from multiprocessing import Process, Pipe, current_process
2835 from multiprocessing.connection import wait
2836
2837 def foo(w):
2838 for i in range(10):
2839 w.send((i, current_process().name))
2840 w.close()
2841
2842 if __name__ == '__main__':
2843 readers = []
2844
2845 for i in range(4):
2846 r, w = Pipe(duplex=False)
2847 readers.append(r)
2848 p = Process(target=foo, args=(w,))
2849 p.start()
2850 # We close the writable end of the pipe now to be sure that
2851 # p is the only process which owns a handle for it. This
2852 # ensures that when p closes its handle for the writable end,
2853 # wait() will promptly report the readable end as being ready.
2854 w.close()
2855
2856 while readers:
2857 for r in wait(readers):
2858 try:
2859 msg = r.recv()
2860 except EOFError:
2861 readers.remove(r)
2862 else:
2863 print(msg)
2864
2865
2866 .. _multiprocessing-address-formats:
2867
2868 Address Formats
2869 """""""""""""""
2870
2871 * An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
2872 *hostname* is a string and *port* is an integer.
2873
2874 * An ``'AF_UNIX'`` address is a string representing a filename on the
2875 filesystem.
2876
2877 * An ``'AF_PIPE'`` address is a string of the form
2878 :samp:`r'\\\\\\.\\pipe\\\\{PipeName}'`. To use :func:`Client` to connect to a named
2879 pipe on a remote computer called *ServerName* one should use an address of the
2880 form :samp:`r'\\\\\\\\{ServerName}\\pipe\\\\{PipeName}'` instead.
2881
2882 Note that any string beginning with two backslashes is assumed by default to be
2883 an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
2884
2885
2886 .. _multiprocessing-auth-keys:
2887
2888 Authentication keys
2889 ^^^^^^^^^^^^^^^^^^^
2890
2891 When one uses :meth:`Connection.recv <Connection.recv>`, the
2892 data received is automatically
2893 unpickled. Unfortunately unpickling data from an untrusted source is a security
2894 risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
2895 to provide digest authentication.
2896
2897 An authentication key is a byte string which can be thought of as a
2898 password: once a connection is established both ends will demand proof
2899 that the other knows the authentication key. (Demonstrating that both
2900 ends are using the same key does **not** involve sending the key over
2901 the connection.)
2902
2903 If authentication is requested but no authentication key is specified then the
2904 return value of ``current_process().authkey`` is used (see
2905 :class:`~multiprocessing.Process`). This value will be automatically inherited by
2906 any :class:`~multiprocessing.Process` object that the current process creates.
2907 This means that (by default) all processes of a multi-process program will share
2908 a single authentication key which can be used when setting up connections
2909 between themselves.
2910
2911 Suitable authentication keys can also be generated by using :func:`os.urandom`.
2912
2913 This authentication protects :class:`Listener` and :func:`Client` connections,
2914 which are reachable by address. It is not applied to the anonymous pipes
2915 created by :func:`~multiprocessing.Pipe` or used internally by
2916 :class:`~multiprocessing.Queue`.
2917 :mod:`multiprocessing` treats all local processes running as the same user as
2918 trusted; on most operating systems such processes can access each other's pipe
2919 file descriptors regardless. Applications that require isolation between
2920 processes of the same user must arrange it at the operating-system level --
2921 for example, by running workers under a different user account or in a sandbox.
2922
2923
2924 Logging
2925 ^^^^^^^
2926
2927 Some support for logging is available. Note, however, that the :mod:`logging`
2928 package does not use process shared locks so it is possible (depending on the
2929 handler type) for messages from different processes to get mixed up.
2930
2931 .. currentmodule:: multiprocessing
2932 .. function:: get_logger()
2933
2934 Returns the logger used by :mod:`!multiprocessing`. If necessary, a new one
2935 will be created.
2936
2937 When first created the logger has level :const:`logging.NOTSET` and no
2938 default handler. Messages sent to this logger will not by default propagate
2939 to the root logger.
2940
2941 Note that on Windows child processes will only inherit the level of the
2942 parent process's logger -- any other customization of the logger will not be
2943 inherited.
2944
2945 .. currentmodule:: multiprocessing
2946 .. function:: log_to_stderr(level=None)
2947
2948 This function performs a call to :func:`get_logger` but in addition to
2949 returning the logger created by get_logger, it adds a handler which sends
2950 output to :data:`sys.stderr` using format
2951 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2952 You can modify ``levelname`` of the logger by passing a ``level`` argument.
2953
2954 Below is an example session with logging turned on::
2955
2956 >>> import multiprocessing, logging
2957 >>> logger = multiprocessing.log_to_stderr()
2958 >>> logger.setLevel(logging.INFO)
2959 >>> logger.warning('doomed')
2960 [WARNING/MainProcess] doomed
2961 >>> m = multiprocessing.Manager()
2962 [INFO/SyncManager-...] child process calling self.run()
2963 [INFO/SyncManager-...] created temp directory /.../pymp-...
2964 [INFO/SyncManager-...] manager serving at '/.../listener-...'
2965 >>> del m
2966 [INFO/MainProcess] sending shutdown message to manager
2967 [INFO/SyncManager-...] manager exiting with exitcode 0
2968
2969 For a full table of logging levels, see the :mod:`logging` module.
2970
2971
2972 The :mod:`!multiprocessing.dummy` module
2973 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2974
2975 .. module:: multiprocessing.dummy
2976 :synopsis: Dumb wrapper around threading.
2977
2978 :mod:`!multiprocessing.dummy` replicates the API of :mod:`!multiprocessing` but is
2979 no more than a wrapper around the :mod:`threading` module.
2980
2981 .. currentmodule:: multiprocessing.pool
2982
2983 In particular, the ``Pool`` function provided by :mod:`!multiprocessing.dummy`
2984 returns an instance of :class:`ThreadPool`, which is a subclass of
2985 :class:`Pool` that supports all the same method calls but uses a pool of
2986 worker threads rather than worker processes.
2987
2988
2989 .. class:: ThreadPool([processes[, initializer[, initargs]]])
2990
2991 A thread pool object which controls a pool of worker threads to which jobs
2992 can be submitted. :class:`ThreadPool` instances are fully interface
2993 compatible with :class:`Pool` instances, and their resources must also be
2994 properly managed, either by using the pool as a context manager or by
2995 calling :meth:`~multiprocessing.pool.Pool.close` and
2996 :meth:`~multiprocessing.pool.Pool.terminate` manually.
2997
2998 *processes* is the number of worker threads to use. If *processes* is
2999 ``None`` then the number returned by :func:`os.process_cpu_count` is used.
3000
3001 If *initializer* is not ``None`` then each worker process will call
3002 ``initializer(*initargs)`` when it starts.
3003
3004 Unlike :class:`Pool`, *maxtasksperchild* and *context* cannot be provided.
3005
3006 .. note::
3007
3008 A :class:`ThreadPool` shares the same interface as :class:`Pool`, which
3009 is designed around a pool of processes and predates the introduction of
3010 the :class:`concurrent.futures` module. As such, it inherits some
3011 operations that don't make sense for a pool backed by threads, and it
3012 has its own type for representing the status of asynchronous jobs,
3013 :class:`AsyncResult`, that is not understood by any other libraries.
3014
3015 Users should generally prefer to use
3016 :class:`concurrent.futures.ThreadPoolExecutor`, which has a simpler
3017 interface that was designed around threads from the start, and which
3018 returns :class:`concurrent.futures.Future` instances that are
3019 compatible with many other libraries, including :mod:`asyncio`.
3020
3021
3022 .. _multiprocessing-programming:
3023
3024 Programming guidelines
3025 ----------------------
3026
3027 There are certain guidelines and idioms which should be adhered to when using
3028 :mod:`!multiprocessing`.
3029
3030
3031 All start methods
3032 ^^^^^^^^^^^^^^^^^
3033
3034 The following applies to all start methods.
3035
3036 Avoid shared state
3037
3038 As far as possible one should try to avoid shifting large amounts of data
3039 between processes.
3040
3041 It is probably best to stick to using queues or pipes for communication
3042 between processes rather than using the lower level synchronization
3043 primitives.
3044
3045 Picklability
3046
3047 Ensure that the arguments to the methods of proxies are picklable.
3048
3049 Thread safety of proxies
3050
3051 Do not use a proxy object from more than one thread unless you protect it
3052 with a lock.
3053
3054 (There is never a problem with different processes using the *same* proxy.)
3055
3056 Joining zombie processes
3057
3058 On POSIX when a process finishes but has not been joined it becomes a zombie.
3059 There should never be very many because each time a new process starts (or
3060 :func:`~multiprocessing.active_children` is called) all completed processes
3061 which have not yet been joined will be joined. Also calling a finished
3062 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
3063 join the process. Even so it is probably good
3064 practice to explicitly join all the processes that you start.
3065
3066 Better to inherit than pickle/unpickle
3067
3068 When using the *spawn* or *forkserver* start methods many types
3069 from :mod:`!multiprocessing` need to be picklable so that child
3070 processes can use them. However, one should generally avoid
3071 sending shared objects to other processes using pipes or queues.
3072 Instead you should arrange the program so that a process which
3073 needs access to a shared resource created elsewhere can inherit it
3074 from an ancestor process.
3075
3076 Avoid terminating processes
3077
3078 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
3079 method to stop a process is liable to
3080 cause any shared resources (such as locks, semaphores, pipes and queues)
3081 currently being used by the process to become broken or unavailable to other
3082 processes.
3083
3084 Therefore it is probably best to only consider using
3085 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
3086 which never use any shared resources.
3087
3088 Joining processes that use queues
3089
3090 Bear in mind that a process that has put items in a queue will wait before
3091 terminating until all the buffered items are fed by the "feeder" thread to
3092 the underlying pipe. (The child process can call the
3093 :meth:`Queue.cancel_join_thread <multiprocessing.Queue.cancel_join_thread>`
3094 method of the queue to avoid this behaviour.)
3095
3096 This means that whenever you use a queue you need to make sure that all
3097 items which have been put on the queue will eventually be removed before the
3098 process is joined. Otherwise you cannot be sure that processes which have
3099 put items on the queue will terminate. Remember also that non-daemonic
3100 processes will be joined automatically.
3101
3102 An example which will deadlock is the following::
3103
3104 from multiprocessing import Process, Queue
3105
3106 def f(q):
3107 q.put('X' * 1000000)
3108
3109 if __name__ == '__main__':
3110 queue = Queue()
3111 p = Process(target=f, args=(queue,))
3112 p.start()
3113 p.join() # this deadlocks
3114 obj = queue.get()
3115
3116 A fix here would be to swap the last two lines (or simply remove the
3117 ``p.join()`` line).
3118
3119 Explicitly pass resources to child processes
3120
3121 On POSIX using the *fork* start method, a child process can make
3122 use of a shared resource created in a parent process using a
3123 global resource. However, it is better to pass the object as an
3124 argument to the constructor for the child process.
3125
3126 Apart from making the code (potentially) compatible with Windows
3127 and the other start methods this also ensures that as long as the
3128 child process is still alive the object will not be garbage
3129 collected in the parent process. This might be important if some
3130 resource is freed when the object is garbage collected in the
3131 parent process.
3132
3133 So for instance ::
3134
3135 from multiprocessing import Process, Lock
3136
3137 def f():
3138 ... do something using "lock" ...
3139
3140 if __name__ == '__main__':
3141 lock = Lock()
3142 for i in range(10):
3143 Process(target=f).start()
3144
3145 should be rewritten as ::
3146
3147 from multiprocessing import Process, Lock
3148
3149 def f(l):
3150 ... do something using "l" ...
3151
3152 if __name__ == '__main__':
3153 lock = Lock()
3154 for i in range(10):
3155 Process(target=f, args=(lock,)).start()
3156
3157 Beware of replacing :data:`sys.stdin` with a "file like object"
3158
3159 :mod:`!multiprocessing` originally unconditionally called::
3160
3161 os.close(sys.stdin.fileno())
3162
3163 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
3164 in issues with processes-in-processes. This has been changed to::
3165
3166 sys.stdin.close()
3167 sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)
3168
3169 Which solves the fundamental issue of processes colliding with each other
3170 resulting in a bad file descriptor error, but introduces a potential danger
3171 to applications which replace :func:`sys.stdin` with a "file-like object"
3172 with output buffering. This danger is that if multiple processes call
3173 :meth:`~io.IOBase.close` on this file-like object, it could result in the same
3174 data being flushed to the object multiple times, resulting in corruption.
3175
3176 If you write a file-like object and implement your own caching, you can
3177 make it fork-safe by storing the pid whenever you append to the cache,
3178 and discarding the cache when the pid changes. For example::
3179
3180 @property
3181 def cache(self):
3182 pid = os.getpid()
3183 if pid != self._pid:
3184 self._pid = pid
3185 self._cache = []
3186 return self._cache
3187
3188 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
3189
3190 .. _multiprocessing-programming-spawn:
3191 .. _multiprocessing-programming-forkserver:
3192
3193 The *spawn* and *forkserver* start methods
3194 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3195
3196 There are a few extra restrictions which don't apply to the *fork*
3197 start method.
3198
3199 More picklability
3200
3201 Ensure that all arguments to :class:`~multiprocessing.Process` are
3202 picklable. Also, if you subclass ``Process.__init__``, you must make sure
3203 that instances will be picklable when the
3204 :meth:`Process.start <multiprocessing.Process.start>` method is called.
3205
3206 Global variables
3207
3208 Bear in mind that if code run in a child process tries to access a global
3209 variable, then the value it sees (if any) may not be the same as the value
3210 in the parent process at the time that :meth:`Process.start
3211 <multiprocessing.Process.start>` was called.
3212
3213 However, global variables which are just module level constants cause no
3214 problems.
3215
3216 .. _multiprocessing-safe-main-import:
3217
3218 Safe importing of main module
3219
3220 Make sure that the main module can be safely imported by a new Python
3221 interpreter without causing unintended side effects (such as starting a new
3222 process).
3223
3224 For example, using the *spawn* or *forkserver* start method
3225 running the following module would fail with a
3226 :exc:`RuntimeError`::
3227
3228 from multiprocessing import Process
3229
3230 def foo():
3231 print('hello')
3232
3233 p = Process(target=foo)
3234 p.start()
3235
3236 Instead one should protect the "entry point" of the program by using ``if
3237 __name__ == '__main__':`` as follows::
3238
3239 from multiprocessing import Process, freeze_support, set_start_method
3240
3241 def foo():
3242 print('hello')
3243
3244 if __name__ == '__main__':
3245 freeze_support()
3246 set_start_method('spawn')
3247 p = Process(target=foo)
3248 p.start()
3249
3250 (The ``freeze_support()`` line can be omitted if the program will be run
3251 normally instead of frozen.)
3252
3253 This allows the newly spawned Python interpreter to safely import the module
3254 and then run the module's ``foo()`` function.
3255
3256 Similar restrictions apply if a pool or manager is created in the main
3257 module.
3258
3259
3260 .. _multiprocessing-examples:
3261
3262 Examples
3263 --------
3264
3265 Demonstration of how to create and use customized managers and proxies:
3266
3267 .. literalinclude:: ../includes/mp_newtype.py
3268 :language: python3
3269
3270
3271 Using :class:`~multiprocessing.pool.Pool`:
3272
3273 .. literalinclude:: ../includes/mp_pool.py
3274 :language: python3
3275
3276
3277 An example showing how to use queues to feed tasks to a collection of worker
3278 processes and collect the results:
3279
3280 .. literalinclude:: ../includes/mp_workers.py