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