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 unpickleable from within
104 the child process. If you tried typing the above example directly into a REPL it
105 could lead to an :exc:`AttributeError` in the child process trying to locate the
106 *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` and :meth:`~queue.Queue.join`.
903
904 .. method:: qsize()
905
906 Return the approximate size of the queue. Because of
907 multithreading/multiprocessing semantics, this number is not reliable.
908
909 Note that this may raise :exc:`NotImplementedError` on platforms like
910 macOS where ``sem_getvalue()`` is not implemented.
911
912 .. method:: empty()
913
914 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
915 multithreading/multiprocessing semantics, this is not reliable.
916
917 May raise an :exc:`OSError` on closed queues. (not guaranteed)
918
919 .. method:: full()
920
921 Return ``True`` if the queue is full, ``False`` otherwise. Because of
922 multithreading/multiprocessing semantics, this is not reliable.
923
924 .. method:: put(obj[, block[, timeout]])
925
926 Put obj into the queue. If the optional argument *block* is ``True``
927 (the default) and *timeout* is ``None`` (the default), block if necessary until
928 a free slot is available. If *timeout* is a positive number, it blocks at
929 most *timeout* seconds and raises the :exc:`queue.Full` exception if no
930 free slot was available within that time. Otherwise (*block* is
931 ``False``), put an item on the queue if a free slot is immediately
932 available, else raise the :exc:`queue.Full` exception (*timeout* is
933 ignored in that case).
934
935 .. versionchanged:: 3.8
936 If the queue is closed, :exc:`ValueError` is raised instead of
937 :exc:`AssertionError`.
938
939 .. method:: put_nowait(obj)
940
941 Equivalent to ``put(obj, False)``.
942
943 .. method:: get([block[, timeout]])
944
945 Remove and return an item from the queue. If optional args *block* is
946 ``True`` (the default) and *timeout* is ``None`` (the default), block if
947 necessary until an item is available. If *timeout* is a positive number,
948 it blocks at most *timeout* seconds and raises the :exc:`queue.Empty`
949 exception if no item was available within that time. Otherwise (block is
950 ``False``), return an item if one is immediately available, else raise the
951 :exc:`queue.Empty` exception (*timeout* is ignored in that case).
952
953 .. versionchanged:: 3.8
954 If the queue is closed, :exc:`ValueError` is raised instead of
955 :exc:`OSError`.
956
957 .. method:: get_nowait()
958
959 Equivalent to ``get(False)``.
960
961 :class:`multiprocessing.Queue` has a few additional methods not found in
962 :class:`queue.Queue`. These methods are usually unnecessary for most
963 code:
964
965 .. method:: close()
966
967 Close the queue: release internal resources.
968
969 A queue must not be used anymore after it is closed. For example,
970 :meth:`~Queue.get`, :meth:`~Queue.put` and :meth:`~Queue.empty`
971 methods must no longer be called.
972
973 The background thread will quit once it has flushed all buffered
974 data to the pipe. This is called automatically when the queue is garbage
975 collected.
976
977 .. method:: join_thread()
978
979 Join the background thread. This can only be used after :meth:`close` has
980 been called. It blocks until the background thread exits, ensuring that
981 all data in the buffer has been flushed to the pipe.
982
983 By default if a process is not the creator of the queue then on exit it
984 will attempt to join the queue's background thread. The process can call
985 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
986
987 .. method:: cancel_join_thread()
988
989 Prevent :meth:`join_thread` from blocking. In particular, this prevents
990 the background thread from being joined automatically when the process
991 exits -- see :meth:`join_thread`.
992
993 A better name for this method might be
994 ``allow_exit_without_flush()``. It is likely to cause enqueued
995 data to be lost, and you almost certainly will not need to use it.
996 It is really only there if you need the current process to exit
997 immediately without waiting to flush enqueued data to the
998 underlying pipe, and you don't care about lost data.
999
1000 .. note::
1001
1002 This class's functionality requires a functioning shared semaphore
1003 implementation on the host operating system. Without one, the
1004 functionality in this class will be disabled, and attempts to
1005 instantiate a :class:`Queue` will result in an :exc:`ImportError`. See
1006 :issue:`3770` for additional information. The same holds true for any
1007 of the specialized queue types listed below.
1008
1009 .. class:: SimpleQueue()
1010
1011 It is a simplified :class:`Queue` type, very close to a locked :class:`Pipe`.
1012
1013 Instantiating this class may set the global start method. See
1014 :ref:`global-start-method` for more details.
1015
1016 .. method:: close()
1017
1018 Close the queue: release internal resources.
1019
1020 A queue must not be used anymore after it is closed. For example,
1021 :meth:`get`, :meth:`put` and :meth:`empty` methods must no longer be
1022 called.
1023
1024 .. versionadded:: 3.9
1025
1026 .. method:: empty()
1027
1028 Return ``True`` if the queue is empty, ``False`` otherwise.
1029
1030 Always raises an :exc:`OSError` if the SimpleQueue is closed.
1031
1032 .. method:: get()
1033
1034 Remove and return an item from the queue.
1035
1036 .. method:: put(item)
1037
1038 Put *item* into the queue.
1039
1040
1041 .. class:: JoinableQueue([maxsize])
1042
1043 :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which
1044 additionally has :meth:`task_done` and :meth:`join` methods.
1045
1046 Instantiating this class may set the global start method. See
1047 :ref:`global-start-method` for more details.
1048
1049 .. method:: task_done()
1050
1051 Indicate that a formerly enqueued task is complete. Used by queue
1052 consumers. For each :meth:`~Queue.get` used to fetch a task, a subsequent
1053 call to :meth:`task_done` tells the queue that the processing on the task
1054 is complete.
1055
1056 If a :meth:`~queue.Queue.join` is currently blocking, it will resume when all
1057 items have been processed (meaning that a :meth:`task_done` call was
1058 received for every item that had been :meth:`~Queue.put` into the queue).
1059
1060 Raises a :exc:`ValueError` if called more times than there were items
1061 placed in the queue.
1062
1063
1064 .. method:: join()
1065
1066 Block until all items in the queue have been gotten and processed.
1067
1068 The count of unfinished tasks goes up whenever an item is added to the
1069 queue. The count goes down whenever a consumer calls
1070 :meth:`task_done` to indicate that the item was retrieved and all work on
1071 it is complete. When the count of unfinished tasks drops to zero,
1072 :meth:`~queue.Queue.join` unblocks.
1073
1074
1075 Miscellaneous
1076 ^^^^^^^^^^^^^
1077
1078 .. function:: active_children()
1079
1080 Return list of all live children of the current process.
1081
1082 Calling this has the side effect of "joining" any processes which have
1083 already finished.
1084
1085 .. function:: cpu_count()
1086
1087 Return the number of CPUs in the system.
1088
1089 This number is not equivalent to the number of CPUs the current process can
1090 use. The number of usable CPUs can be obtained with
1091 :func:`os.process_cpu_count` (or ``len(os.sched_getaffinity(0))``).
1092
1093 When the number of CPUs cannot be determined a :exc:`NotImplementedError`
1094 is raised.
1095
1096 .. seealso::
1097 :func:`os.cpu_count`
1098 :func:`os.process_cpu_count`
1099
1100 .. versionchanged:: 3.13
1101
1102 The return value can also be overridden using the
1103 :option:`-X cpu_count <-X>` flag or :envvar:`PYTHON_CPU_COUNT` as this is
1104 merely a wrapper around the :mod:`os` cpu count APIs.
1105
1106 .. function:: current_process()
1107
1108 Return the :class:`Process` object corresponding to the current process.
1109
1110 An analogue of :func:`threading.current_thread`.
1111
1112 .. function:: parent_process()
1113
1114 Return the :class:`Process` object corresponding to the parent process of
1115 the :func:`current_process`. For the main process, ``parent_process`` will
1116 be ``None``.
1117
1118 .. versionadded:: 3.8
1119
1120 .. function:: freeze_support()
1121
1122 Add support for when a program which uses :mod:`multiprocessing` has been
1123 frozen to produce an executable. (Has been tested with **py2exe**,
1124 **PyInstaller** and **cx_Freeze**.)
1125
1126 One needs to call this function straight after the ``if __name__ ==
1127 '__main__'`` line of the main module. For example::
1128
1129 from multiprocessing import Process, freeze_support
1130
1131 def f():
1132 print('hello world!')
1133
1134 if __name__ == '__main__':
1135 freeze_support()
1136 Process(target=f).start()
1137
1138 If the ``freeze_support()`` line is omitted then trying to run the frozen
1139 executable will raise :exc:`RuntimeError`.
1140
1141 Calling ``freeze_support()`` has no effect when the start method is not
1142 *spawn*. In addition, if the module is being run normally by the Python
1143 interpreter (the program has not been frozen), then ``freeze_support()``
1144 has no effect.
1145
1146 .. function:: get_all_start_methods()
1147
1148 Returns a list of the supported start methods, the first of which
1149 is the default. The possible start methods are ``'fork'``,
1150 ``'spawn'`` and ``'forkserver'``. Not all platforms support all
1151 methods. See :ref:`multiprocessing-start-methods`.
1152
1153 .. versionadded:: 3.4
1154
1155 .. function:: get_context(method=None)
1156
1157 Return a context object which has the same attributes as the
1158 :mod:`multiprocessing` module.
1159
1160 If *method* is ``None`` then the default context is returned. Note that if
1161 the global start method has not been set, this will set it to the system default
1162 See :ref:`global-start-method` for more details.
1163 Otherwise *method* should be ``'fork'``, ``'spawn'``,
1164 ``'forkserver'``. :exc:`ValueError` is raised if the specified
1165 start method is not available. See :ref:`multiprocessing-start-methods`.
1166
1167 .. versionadded:: 3.4
1168
1169 .. function:: get_start_method(allow_none=False)
1170
1171 Return the name of start method used for starting processes.
1172
1173 If the global start method is not set and *allow_none* is ``False``, the global start
1174 method is set to the default, and its name is returned. See
1175 :ref:`global-start-method` for more details.
1176
1177 The return value can be ``'fork'``, ``'spawn'``, ``'forkserver'``
1178 or ``None``. See :ref:`multiprocessing-start-methods`.
1179
1180 .. versionadded:: 3.4
1181
1182 .. versionchanged:: 3.8
1183
1184 On macOS, the *spawn* start method is now the default. The *fork* start
1185 method should be considered unsafe as it can lead to crashes of the
1186 subprocess. See :issue:`33725`.
1187
1188 .. function:: set_executable(executable)
1189
1190 Set the path of the Python interpreter to use when starting a child process.
1191 (By default :data:`sys.executable` is used). Embedders will probably need to
1192 do some thing like ::
1193
1194 set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
1195
1196 before they can create child processes.
1197
1198 .. versionchanged:: 3.4
1199 Now supported on POSIX when the ``'spawn'`` start method is used.
1200
1201 .. versionchanged:: 3.11
1202 Accepts a :term:`path-like object`.
1203
1204 .. function:: set_forkserver_preload(module_names)
1205
1206 Set a list of module names for the forkserver main process to attempt to
1207 import so that their already imported state is inherited by forked
1208 processes. Any :exc:`ImportError` when doing so is silently ignored.
1209 This can be used as a performance enhancement to avoid repeated work
1210 in every process.
1211
1212 For this to work, it must be called before the forkserver process has been
1213 launched (before creating a :class:`Pool` or starting a :class:`Process`).
1214
1215 Only meaningful when using the ``'forkserver'`` start method.
1216 See :ref:`multiprocessing-start-methods`.
1217
1218 .. versionadded:: 3.4
1219
1220 .. function:: set_start_method(method, force=False)
1221
1222 Set the method which should be used to start child processes.
1223 The *method* argument can be ``'fork'``, ``'spawn'`` or ``'forkserver'``.
1224 Raises :exc:`RuntimeError` if the start method has already been set and *force*
1225 is not ``True``. If *method* is ``None`` and *force* is ``True`` then the start
1226 method is set to ``None``. If *method* is ``None`` and *force* is ``False``
1227 then the context is set to the default context.
1228
1229 Note that this should be called at most once, and it should be
1230 protected inside the ``if __name__ == '__main__'`` clause of the
1231 main module.
1232
1233 See :ref:`multiprocessing-start-methods`.
1234
1235 .. versionadded:: 3.4
1236
1237 .. note::
1238
1239 :mod:`multiprocessing` contains no analogues of
1240 :func:`threading.active_count`, :func:`threading.enumerate`,
1241 :func:`threading.settrace`, :func:`threading.setprofile`,
1242 :class:`threading.Timer`, or :class:`threading.local`.
1243
1244
1245 Connection Objects
1246 ^^^^^^^^^^^^^^^^^^
1247
1248 .. currentmodule:: multiprocessing.connection
1249
1250 Connection objects allow the sending and receiving of picklable objects or
1251 strings. They can be thought of as message oriented connected sockets.
1252
1253 Connection objects are usually created using
1254 :func:`Pipe <multiprocessing.Pipe>` -- see also
1255 :ref:`multiprocessing-listeners-clients`.
1256
1257 .. class:: Connection
1258
1259 .. method:: send(obj)
1260
1261 Send an object to the other end of the connection which should be read
1262 using :meth:`recv`.
1263
1264 The object must be picklable. Very large pickles (approximately 32 MiB+,
1265 though it depends on the OS) may raise a :exc:`ValueError` exception.
1266
1267 .. method:: recv()
1268
1269 Return an object sent from the other end of the connection using
1270 :meth:`send`. Blocks until there is something to receive. Raises
1271 :exc:`EOFError` if there is nothing left to receive
1272 and the other end was closed.
1273
1274 .. method:: fileno()
1275
1276 Return the file descriptor or handle used by the connection.
1277
1278 .. method:: close()
1279
1280 Close the connection.
1281
1282 This is called automatically when the connection is garbage collected.
1283
1284 .. method:: poll([timeout])
1285
1286 Return whether there is any data available to be read.
1287
1288 If *timeout* is not specified then it will return immediately. If
1289 *timeout* is a number then this specifies the maximum time in seconds to
1290 block. If *timeout* is ``None`` then an infinite timeout is used.
1291
1292 Note that multiple connection objects may be polled at once by
1293 using :func:`multiprocessing.connection.wait`.
1294
1295 .. method:: send_bytes(buffer[, offset[, size]])
1296
1297 Send byte data from a :term:`bytes-like object` as a complete message.
1298
1299 If *offset* is given then data is read from that position in *buffer*. If
1300 *size* is given then that many bytes will be read from buffer. Very large
1301 buffers (approximately 32 MiB+, though it depends on the OS) may raise a
1302 :exc:`ValueError` exception
1303
1304 .. method:: recv_bytes([maxlength])
1305
1306 Return a complete message of byte data sent from the other end of the
1307 connection as a string. Blocks until there is something to receive.
1308 Raises :exc:`EOFError` if there is nothing left
1309 to receive and the other end has closed.
1310
1311 If *maxlength* is specified and the message is longer than *maxlength*
1312 then :exc:`OSError` is raised and the connection will no longer be
1313 readable.
1314
1315 .. versionchanged:: 3.3
1316 This function used to raise :exc:`IOError`, which is now an
1317 alias of :exc:`OSError`.
1318
1319
1320 .. method:: recv_bytes_into(buffer[, offset])
1321
1322 Read into *buffer* a complete message of byte data sent from the other end
1323 of the connection and return the number of bytes in the message. Blocks
1324 until there is something to receive. Raises
1325 :exc:`EOFError` if there is nothing left to receive and the other end was
1326 closed.
1327
1328 *buffer* must be a writable :term:`bytes-like object`. If
1329 *offset* is given then the message will be written into the buffer from
1330 that position. Offset must be a non-negative integer less than the
1331 length of *buffer* (in bytes).
1332
1333 If the buffer is too short then a :exc:`BufferTooShort` exception is
1334 raised and the complete message is available as ``e.args[0]`` where ``e``
1335 is the exception instance.
1336
1337 .. versionchanged:: 3.3
1338 Connection objects themselves can now be transferred between processes
1339 using :meth:`Connection.send` and :meth:`Connection.recv`.
1340
1341 Connection objects also now support the context management protocol -- see
1342 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the
1343 connection object, and :meth:`~contextmanager.__exit__` calls :meth:`close`.
1344
1345 For example:
1346
1347 .. doctest::
1348
1349 >>> from multiprocessing import Pipe
1350 >>> a, b = Pipe()
1351 >>> a.send([1, 'hello', None])
1352 >>> b.recv()
1353 [1, 'hello', None]
1354 >>> b.send_bytes(b'thank you')
1355 >>> a.recv_bytes()
1356 b'thank you'
1357 >>> import array
1358 >>> arr1 = array.array('i', range(5))
1359 >>> arr2 = array.array('i', [0] * 10)
1360 >>> a.send_bytes(arr1)
1361 >>> count = b.recv_bytes_into(arr2)
1362 >>> assert count == len(arr1) * arr1.itemsize
1363 >>> arr2
1364 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
1365
1366 .. _multiprocessing-recv-pickle-security:
1367
1368 .. warning::
1369
1370 The :meth:`Connection.recv` method automatically unpickles the data it
1371 receives, which can be a security risk unless you can trust the process
1372 which sent the message.
1373
1374 Therefore, unless the connection object was produced using :func:`Pipe` you
1375 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
1376 methods after performing some sort of authentication. See
1377 :ref:`multiprocessing-auth-keys`.
1378
1379 .. warning::
1380
1381 If a process is killed while it is trying to read or write to a pipe then
1382 the data in the pipe is likely to become corrupted, because it may become
1383 impossible to be sure where the message boundaries lie.
1384
1385
1386 Synchronization primitives
1387 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1388
1389 .. currentmodule:: multiprocessing
1390
1391 Generally synchronization primitives are not as necessary in a multiprocess
1392 program as they are in a multithreaded program. See the documentation for
1393 :mod:`threading` module.
1394
1395 Note that one can also create synchronization primitives by using a manager
1396 object -- see :ref:`multiprocessing-managers`.
1397
1398 .. class:: Barrier(parties[, action[, timeout]])
1399
1400 A barrier object: a clone of :class:`threading.Barrier`.
1401
1402 Instantiating this class may set the global start method. See
1403 :ref:`global-start-method` for more details.
1404
1405 .. versionadded:: 3.3
1406
1407 .. class:: BoundedSemaphore([value])
1408
1409 A bounded semaphore object: a close analog of
1410 :class:`threading.BoundedSemaphore`.
1411
1412 Instantiating this class may set the global start method. See
1413 :ref:`global-start-method` for more details.
1414
1415 A solitary difference from its close analog exists: its ``acquire`` method's
1416 first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
1417
1418 .. note::
1419 On macOS, this is indistinguishable from :class:`Semaphore` because
1420 ``sem_getvalue()`` is not implemented on that platform.
1421
1422 .. class:: Condition([lock])
1423
1424 A condition variable: an alias for :class:`threading.Condition`.
1425
1426 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
1427 object from :mod:`multiprocessing`.
1428
1429 Instantiating this class may set the global start method. See
1430 :ref:`global-start-method` for more details.
1431
1432 .. versionchanged:: 3.3
1433 The :meth:`~threading.Condition.wait_for` method was added.
1434
1435 .. class:: Event()
1436
1437 A clone of :class:`threading.Event`.
1438
1439 Instantiating this class may set the global start method. See
1440 :ref:`global-start-method` for more details.
1441
1442 .. class:: Lock()
1443
1444 A non-recursive lock object: a close analog of :class:`threading.Lock`.
1445 Once a process or thread has acquired a lock, subsequent attempts to
1446 acquire it from any process or thread will block until it is released;
1447 any process or thread may release it. The concepts and behaviors of
1448 :class:`threading.Lock` as it applies to threads are replicated here in
1449 :class:`multiprocessing.Lock` as it applies to either processes or threads,
1450 except as noted.
1451
1452 Note that :class:`Lock` is actually a factory function which returns an
1453 instance of ``multiprocessing.synchronize.Lock`` initialized with a
1454 default context.
1455
1456 Instantiating this class may set the global start method. See
1457 :ref:`global-start-method` for more details.
1458
1459 :class:`Lock` supports the :term:`context manager` protocol and thus may be
1460 used in :keyword:`with` statements.
1461
1462 .. method:: acquire(block=True, timeout=None)
1463
1464 Acquire a lock, blocking or non-blocking.
1465
1466 With the *block* argument set to ``True`` (the default), the method call
1467 will block until the lock is in an unlocked state, then set it to locked
1468 and return ``True``. Note that the name of this first argument differs
1469 from that in :meth:`threading.Lock.acquire`.
1470
1471 With the *block* argument set to ``False``, the method call does not
1472 block. If the lock is currently in a locked state, return ``False``;
1473 otherwise set the lock to a locked state and return ``True``.
1474
1475 When invoked with a positive, floating-point value for *timeout*, block
1476 for at most the number of seconds specified by *timeout* as long as
1477 the lock can not be acquired. Invocations with a negative value for
1478 *timeout* are equivalent to a *timeout* of zero. Invocations with a
1479 *timeout* value of ``None`` (the default) set the timeout period to
1480 infinite. Note that the treatment of negative or ``None`` values for
1481 *timeout* differs from the implemented behavior in
1482 :meth:`threading.Lock.acquire`. The *timeout* argument has no practical
1483 implications if the *block* argument is set to ``False`` and is thus
1484 ignored. Returns ``True`` if the lock has been acquired or ``False`` if
1485 the timeout period has elapsed.
1486
1487
1488 .. method:: release()
1489
1490 Release a lock. This can be called from any process or thread, not only
1491 the process or thread which originally acquired the lock.
1492
1493 Behavior is the same as in :meth:`threading.Lock.release` except that
1494 when invoked on an unlocked lock, a :exc:`ValueError` is raised.
1495
1496
1497 .. class:: RLock()
1498
1499 A recursive lock object: a close analog of :class:`threading.RLock`. A
1500 recursive lock must be released by the process or thread that acquired it.
1501 Once a process or thread has acquired a recursive lock, the same process
1502 or thread may acquire it again without blocking; that process or thread
1503 must release it once for each time it has been acquired.
1504
1505 Note that :class:`RLock` is actually a factory function which returns an
1506 instance of ``multiprocessing.synchronize.RLock`` initialized with a
1507 default context.
1508
1509 Instantiating this class may set the global start method. See
1510 :ref:`global-start-method` for more details.
1511
1512 :class:`RLock` supports the :term:`context manager` protocol and thus may be
1513 used in :keyword:`with` statements.
1514
1515
1516 .. method:: acquire(block=True, timeout=None)
1517
1518 Acquire a lock, blocking or non-blocking.
1519
1520 When invoked with the *block* argument set to ``True``, block until the
1521 lock is in an unlocked state (not owned by any process or thread) unless
1522 the lock is already owned by the current process or thread. The current
1523 process or thread then takes ownership of the lock (if it does not
1524 already have ownership) and the recursion level inside the lock increments
1525 by one, resulting in a return value of ``True``. Note that there are
1526 several differences in this first argument's behavior compared to the
1527 implementation of :meth:`threading.RLock.acquire`, starting with the name
1528 of the argument itself.
1529
1530 When invoked with the *block* argument set to ``False``, do not block.
1531 If the lock has already been acquired (and thus is owned) by another
1532 process or thread, the current process or thread does not take ownership
1533 and the recursion level within the lock is not changed, resulting in
1534 a return value of ``False``. If the lock is in an unlocked state, the
1535 current process or thread takes ownership and the recursion level is
1536 incremented, resulting in a return value of ``True``.
1537
1538 Use and behaviors of the *timeout* argument are the same as in
1539 :meth:`Lock.acquire`. Note that some of these behaviors of *timeout*
1540 differ from the implemented behaviors in :meth:`threading.RLock.acquire`.
1541
1542
1543 .. method:: release()
1544
1545 Release a lock, decrementing the recursion level. If after the
1546 decrement the recursion level is zero, reset the lock to unlocked (not
1547 owned by any process or thread) and if any other processes or threads
1548 are blocked waiting for the lock to become unlocked, allow exactly one
1549 of them to proceed. If after the decrement the recursion level is still
1550 nonzero, the lock remains locked and owned by the calling process or
1551 thread.
1552
1553 Only call this method when the calling process or thread owns the lock.
1554 An :exc:`AssertionError` is raised if this method is called by a process
1555 or thread other than the owner or if the lock is in an unlocked (unowned)
1556 state. Note that the type of exception raised in this situation
1557 differs from the implemented behavior in :meth:`threading.RLock.release`.
1558
1559
1560 .. class:: Semaphore([value])
1561
1562 A semaphore object: a close analog of :class:`threading.Semaphore`.
1563
1564 Instantiating this class may set the global start method. See
1565 :ref:`global-start-method` for more details.
1566
1567 A solitary difference from its close analog exists: its ``acquire`` method's
1568 first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
1569
1570 .. note::
1571
1572 On macOS, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
1573 a timeout will emulate that function's behavior using a sleeping loop.
1574
1575 .. note::
1576
1577 Some of this package's functionality requires a functioning shared semaphore
1578 implementation on the host operating system. Without one, the
1579 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
1580 import it will result in an :exc:`ImportError`. See
1581 :issue:`3770` for additional information.
1582
1583
1584 Shared :mod:`ctypes` Objects
1585 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1586
1587 It is possible to create shared objects using shared memory which can be
1588 inherited by child processes.
1589
1590 .. function:: Value(typecode_or_type, *args, lock=True)
1591
1592 Return a :mod:`ctypes` object allocated from shared memory. By default the
1593 return value is actually a synchronized wrapper for the object. The object
1594 itself can be accessed via the *value* attribute of a :class:`Value`.
1595
1596 *typecode_or_type* determines the type of the returned object: it is either a
1597 ctypes type or a one character typecode of the kind used by the :mod:`array`
1598 module. *\*args* is passed on to the constructor for the type.
1599
1600 If *lock* is ``True`` (the default) then a new recursive lock
1601 object is created to synchronize access to the value. If *lock* is
1602 a :class:`Lock` or :class:`RLock` object then that will be used to
1603 synchronize access to the value. If *lock* is ``False`` then
1604 access to the returned object will not be automatically protected
1605 by a lock, so it will not necessarily be "process-safe".
1606
1607 Operations like ``+=`` which involve a read and write are not
1608 atomic. So if, for instance, you want to atomically increment a
1609 shared value it is insufficient to just do ::
1610
1611 counter.value += 1
1612
1613 Assuming the associated lock is recursive (which it is by default)
1614 you can instead do ::
1615
1616 with counter.get_lock():
1617 counter.value += 1
1618
1619 Note that *lock* is a keyword-only argument.
1620
1621 .. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
1622
1623 Return a ctypes array allocated from shared memory. By default the return
1624 value is actually a synchronized wrapper for the array.
1625
1626 *typecode_or_type* determines the type of the elements of the returned array:
1627 it is either a :ref:`ctypes type <ctypes-fundamental-data-types>` or a one
1628 character typecode of the kind used by the :mod:`array` module with the
1629 exception of ``'w'``, which is not supported. In addition, the ``'c'``
1630 typecode is an alias for :class:`ctypes.c_char`. If *size_or_initializer*
1631 is an integer, then it determines the length of the array, and the array
1632 will be initially zeroed. Otherwise, *size_or_initializer* is a sequence
1633 which is used to initialize the array and whose length determines the length
1634 of the array.
1635
1636 If *lock* is ``True`` (the default) then a new lock object is created to
1637 synchronize access to the value. If *lock* is a :class:`Lock` or
1638 :class:`RLock` object then that will be used to synchronize access to the
1639 value. If *lock* is ``False`` then access to the returned object will not be
1640 automatically protected by a lock, so it will not necessarily be
1641 "process-safe".
1642
1643 Note that *lock* is a keyword only argument.
1644
1645 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
1646 attributes which allow one to use it to store and retrieve strings.
1647
1648
1649 The :mod:`multiprocessing.sharedctypes` module
1650 """"""""""""""""""""""""""""""""""""""""""""""
1651
1652 .. module:: multiprocessing.sharedctypes
1653 :synopsis: Allocate ctypes objects from shared memory.
1654
1655 The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
1656 :mod:`ctypes` objects from shared memory which can be inherited by child
1657 processes.
1658
1659 .. note::
1660
1661 Although it is possible to store a pointer in shared memory remember that
1662 this will refer to a location in the address space of a specific process.
1663 However, the pointer is quite likely to be invalid in the context of a second
1664 process and trying to dereference the pointer from the second process may
1665 cause a crash.
1666
1667 .. function:: RawArray(typecode_or_type, size_or_initializer)
1668
1669 Return a ctypes array allocated from shared memory.
1670
1671 *typecode_or_type* determines the type of the elements of the returned array:
1672 it is either a ctypes type or a one character typecode of the kind used by
1673 the :mod:`array` module. If *size_or_initializer* is an integer then it
1674 determines the length of the array, and the array will be initially zeroed.
1675 Otherwise *size_or_initializer* is a sequence which is used to initialize the
1676 array and whose length determines the length of the array.
1677
1678 Note that setting and getting an element is potentially non-atomic -- use
1679 :func:`Array` instead to make sure that access is automatically synchronized
1680 using a lock.
1681
1682 .. function:: RawValue(typecode_or_type, *args)
1683
1684 Return a ctypes object allocated from shared memory.
1685
1686 *typecode_or_type* determines the type of the returned object: it is either a
1687 ctypes type or a one character typecode of the kind used by the :mod:`array`
1688 module. *\*args* is passed on to the constructor for the type.
1689
1690 Note that setting and getting the value is potentially non-atomic -- use
1691 :func:`Value` instead to make sure that access is automatically synchronized
1692 using a lock.
1693
1694 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
1695 attributes which allow one to use it to store and retrieve strings -- see
1696 documentation for :mod:`ctypes`.
1697
1698 .. function:: Array(typecode_or_type, size_or_initializer, *, lock=True, ctx=None)
1699
1700 The same as :func:`RawArray` except that depending on the value of *lock* a
1701 process-safe synchronization wrapper may be returned instead of a raw ctypes
1702 array.
1703
1704 If *lock* is ``True`` (the default) then a new lock object is created to
1705 synchronize access to the value. If *lock* is a
1706 :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
1707 then that will be used to synchronize access to the
1708 value. If *lock* is ``False`` then access to the returned object will not be
1709 automatically protected by a lock, so it will not necessarily be
1710 "process-safe".
1711
1712 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1713 calling this may set the global start method. See
1714 :ref:`global-start-method` for more details.
1715
1716 Note that *lock* and *ctx* are keyword-only parameters.
1717
1718 .. function:: Value(typecode_or_type, *args, lock=True, ctx=None)
1719
1720 The same as :func:`RawValue` except that depending on the value of *lock* a
1721 process-safe synchronization wrapper may be returned instead of a raw ctypes
1722 object.
1723
1724 If *lock* is ``True`` (the default) then a new lock object is created to
1725 synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or
1726 :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
1727 value. If *lock* is ``False`` then access to the returned object will not be
1728 automatically protected by a lock, so it will not necessarily be
1729 "process-safe".
1730
1731 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1732 calling this may set the global start method. See
1733 :ref:`global-start-method` for more details.
1734
1735 Note that *lock* and *ctx* are keyword-only parameters.
1736
1737 .. function:: copy(obj)
1738
1739 Return a ctypes object allocated from shared memory which is a copy of the
1740 ctypes object *obj*.
1741
1742 .. function:: synchronized(obj, lock=None, ctx=None)
1743
1744 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1745 synchronize access. If *lock* is ``None`` (the default) then a
1746 :class:`multiprocessing.RLock` object is created automatically.
1747
1748 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1749 calling this may set the global start method. See
1750 :ref:`global-start-method` for more details.
1751
1752 A synchronized wrapper will have two methods in addition to those of the
1753 object it wraps: :meth:`get_obj` returns the wrapped object and
1754 :meth:`get_lock` returns the lock object used for synchronization.
1755
1756 Note that accessing the ctypes object through the wrapper can be a lot slower
1757 than accessing the raw ctypes object.
1758
1759 .. versionchanged:: 3.5
1760 Synchronized objects support the :term:`context manager` protocol.
1761
1762
1763 The table below compares the syntax for creating shared ctypes objects from
1764 shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1765 subclass of :class:`ctypes.Structure`.)
1766
1767 ==================== ========================== ===========================
1768 ctypes sharedctypes using type sharedctypes using typecode
1769 ==================== ========================== ===========================
1770 c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1771 MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1772 (c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1773 (c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1774 ==================== ========================== ===========================
1775
1776
1777 Below is an example where a number of ctypes objects are modified by a child
1778 process::
1779
1780 from multiprocessing import Process, Lock
1781 from multiprocessing.sharedctypes import Value, Array
1782 from ctypes import Structure, c_double
1783
1784 class Point(Structure):
1785 _fields_ = [('x', c_double), ('y', c_double)]
1786
1787 def modify(n, x, s, A):
1788 n.value **= 2
1789 x.value **= 2
1790 s.value = s.value.upper()
1791 for a in A:
1792 a.x **= 2
1793 a.y **= 2
1794
1795 if __name__ == '__main__':
1796 lock = Lock()
1797
1798 n = Value('i', 7)
1799 x = Value(c_double, 1.0/3.0, lock=False)
1800 s = Array('c', b'hello world', lock=lock)
1801 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1802
1803 p = Process(target=modify, args=(n, x, s, A))
1804 p.start()
1805 p.join()
1806
1807 print(n.value)
1808 print(x.value)
1809 print(s.value)
1810 print([(a.x, a.y) for a in A])
1811
1812
1813 .. highlight:: none
1814
1815 The results printed are ::
1816
1817 49
1818 0.1111111111111111
1819 HELLO WORLD
1820 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1821
1822 .. highlight:: python3
1823
1824
1825 .. _multiprocessing-managers:
1826
1827 Managers
1828 ^^^^^^^^
1829
1830 Managers provide a way to create data which can be shared between different
1831 processes, including sharing over a network between processes running on
1832 different machines. A manager object controls a server process which manages
1833 *shared objects*. Other processes can access the shared objects by using
1834 proxies.
1835
1836 .. function:: multiprocessing.Manager()
1837 :module:
1838
1839 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1840 can be used for sharing objects between processes. The returned manager
1841 object corresponds to a spawned child process and has methods which will
1842 create shared objects and return corresponding proxies.
1843
1844 .. module:: multiprocessing.managers
1845 :synopsis: Share data between process with shared objects.
1846
1847 Manager processes will be shutdown as soon as they are garbage collected or
1848 their parent process exits. The manager classes are defined in the
1849 :mod:`multiprocessing.managers` module:
1850
1851 .. class:: BaseManager(address=None, authkey=None, serializer='pickle', ctx=None, *, shutdown_timeout=1.0)
1852
1853 Create a BaseManager object.
1854
1855 Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
1856 that the manager object refers to a started manager process.
1857
1858 *address* is the address on which the manager process listens for new
1859 connections. If *address* is ``None`` then an arbitrary one is chosen.
1860
1861 *authkey* is the authentication key which will be used to check the
1862 validity of incoming connections to the server process. If
1863 *authkey* is ``None`` then ``current_process().authkey`` is used.
1864 Otherwise *authkey* is used and it must be a byte string.
1865
1866 *serializer* must be ``'pickle'`` (use :mod:`pickle` serialization) or
1867 ``'xmlrpclib'`` (use :mod:`xmlrpc.client` serialization).
1868
1869 *ctx* is a context object, or ``None`` (use the current context). If ``None``,
1870 calling this may set the global start method. See
1871 :ref:`global-start-method` for more details.
1872
1873 *shutdown_timeout* is a timeout in seconds used to wait until the process
1874 used by the manager completes in the :meth:`shutdown` method. If the
1875 shutdown times out, the process is terminated. If terminating the process
1876 also times out, the process is killed.
1877
1878 .. versionchanged:: 3.11
1879 Added the *shutdown_timeout* parameter.
1880
1881 .. method:: start([initializer[, initargs]])
1882
1883 Start a subprocess to start the manager. If *initializer* is not ``None``
1884 then the subprocess will call ``initializer(*initargs)`` when it starts.
1885
1886 .. method:: get_server()
1887
1888 Returns a :class:`Server` object which represents the actual server under
1889 the control of the Manager. The :class:`Server` object supports the
1890 :meth:`serve_forever` method::
1891
1892 >>> from multiprocessing.managers import BaseManager
1893 >>> manager = BaseManager(address=('', 50000), authkey=b'abc')
1894 >>> server = manager.get_server()
1895 >>> server.serve_forever()
1896
1897 :class:`Server` additionally has an :attr:`address` attribute.
1898
1899 .. method:: connect()
1900
1901 Connect a local manager object to a remote manager process::
1902
1903 >>> from multiprocessing.managers import BaseManager
1904 >>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
1905 >>> m.connect()
1906
1907 .. method:: shutdown()
1908
1909 Stop the process used by the manager. This is only available if
1910 :meth:`start` has been used to start the server process.
1911
1912 This can be called multiple times.
1913
1914 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1915
1916 A classmethod which can be used for registering a type or callable with
1917 the manager class.
1918
1919 *typeid* is a "type identifier" which is used to identify a particular
1920 type of shared object. This must be a string.
1921
1922 *callable* is a callable used for creating objects for this type
1923 identifier. If a manager instance will be connected to the
1924 server using the :meth:`connect` method, or if the
1925 *create_method* argument is ``False`` then this can be left as
1926 ``None``.
1927
1928 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1929 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1930 class is created automatically.
1931
1932 *exposed* is used to specify a sequence of method names which proxies for
1933 this typeid should be allowed to access using
1934 :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then
1935 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1936 where no exposed list is specified, all "public methods" of the shared
1937 object will be accessible. (Here a "public method" means any attribute
1938 which has a :meth:`~object.__call__` method and whose name does not begin
1939 with ``'_'``.)
1940
1941 *method_to_typeid* is a mapping used to specify the return type of those
1942 exposed methods which should return a proxy. It maps method names to
1943 typeid strings. (If *method_to_typeid* is ``None`` then
1944 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1945 method's name is not a key of this mapping or if the mapping is ``None``
1946 then the object returned by the method will be copied by value.
1947
1948 *create_method* determines whether a method should be created with name
1949 *typeid* which can be used to tell the server process to create a new
1950 shared object and return a proxy for it. By default it is ``True``.
1951
1952 :class:`BaseManager` instances also have one read-only property:
1953
1954 .. attribute:: address
1955
1956 The address used by the manager.
1957
1958 .. versionchanged:: 3.3
1959 Manager objects support the context management protocol -- see
1960 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` starts the
1961 server process (if it has not already started) and then returns the
1962 manager object. :meth:`~contextmanager.__exit__` calls :meth:`shutdown`.
1963
1964 In previous versions :meth:`~contextmanager.__enter__` did not start the
1965 manager's server process if it was not already started.
1966
1967 .. class:: SyncManager
1968
1969 A subclass of :class:`BaseManager` which can be used for the synchronization
1970 of processes. Objects of this type are returned by
1971 :func:`multiprocessing.Manager`.
1972
1973 Its methods create and return :ref:`multiprocessing-proxy_objects` for a
1974 number of commonly used data types to be synchronized across processes.
1975 This notably includes shared lists and dictionaries.
1976
1977 .. method:: Barrier(parties[, action[, timeout]])
1978
1979 Create a shared :class:`threading.Barrier` object and return a
1980 proxy for it.
1981
1982 .. versionadded:: 3.3
1983
1984 .. method:: BoundedSemaphore([value])
1985
1986 Create a shared :class:`threading.BoundedSemaphore` object and return a
1987 proxy for it.
1988
1989 .. method:: Condition([lock])
1990
1991 Create a shared :class:`threading.Condition` object and return a proxy for
1992 it.
1993
1994 If *lock* is supplied then it should be a proxy for a
1995 :class:`threading.Lock` or :class:`threading.RLock` object.
1996
1997 .. versionchanged:: 3.3
1998 The :meth:`~threading.Condition.wait_for` method was added.
1999
2000 .. method:: Event()
2001
2002 Create a shared :class:`threading.Event` object and return a proxy for it.
2003
2004 .. method:: Lock()
2005
2006 Create a shared :class:`threading.Lock` object and return a proxy for it.
2007
2008 .. method:: Namespace()
2009
2010 Create a shared :class:`Namespace` object and return a proxy for it.
2011
2012 .. method:: Queue([maxsize])
2013
2014 Create a shared :class:`queue.Queue` object and return a proxy for it.
2015
2016 .. method:: RLock()
2017
2018 Create a shared :class:`threading.RLock` object and return a proxy for it.
2019
2020 .. method:: Semaphore([value])
2021
2022 Create a shared :class:`threading.Semaphore` object and return a proxy for
2023 it.
2024
2025 .. method:: Array(typecode, sequence)
2026
2027 Create an array and return a proxy for it.
2028
2029 .. method:: Value(typecode, value)
2030
2031 Create an object with a writable ``value`` attribute and return a proxy
2032 for it.
2033
2034 .. method:: dict()
2035 dict(mapping)
2036 dict(sequence)
2037
2038 Create a shared :class:`dict` object and return a proxy for it.
2039
2040 .. method:: list()
2041 list(sequence)
2042
2043 Create a shared :class:`list` object and return a proxy for it.
2044
2045 .. versionchanged:: 3.6
2046 Shared objects are capable of being nested. For example, a shared
2047 container object such as a shared list can contain other shared objects
2048 which will all be managed and synchronized by the :class:`SyncManager`.
2049
2050 .. class:: Namespace
2051
2052 A type that can register with :class:`SyncManager`.
2053
2054 A namespace object has no public methods, but does have writable attributes.
2055 Its representation shows the values of its attributes.
2056
2057 However, when using a proxy for a namespace object, an attribute beginning
2058 with ``'_'`` will be an attribute of the proxy and not an attribute of the
2059 referent:
2060
2061 .. doctest::
2062
2063 >>> mp_context = multiprocessing.get_context('spawn')
2064 >>> manager = mp_context.Manager()
2065 >>> Global = manager.Namespace()
2066 >>> Global.x = 10
2067 >>> Global.y = 'hello'
2068 >>> Global._z = 12.3 # this is an attribute of the proxy
2069 >>> print(Global)
2070 Namespace(x=10, y='hello')
2071
2072
2073 Customized managers
2074 """""""""""""""""""
2075
2076 To create one's own manager, one creates a subclass of :class:`BaseManager` and
2077 uses the :meth:`~BaseManager.register` classmethod to register new types or
2078 callables with the manager class. For example::
2079
2080 from multiprocessing.managers import BaseManager
2081
2082 class MathsClass:
2083 def add(self, x, y):
2084 return x + y
2085 def mul(self, x, y):
2086 return x * y
2087
2088 class MyManager(BaseManager):
2089 pass
2090
2091 MyManager.register('Maths', MathsClass)
2092
2093 if __name__ == '__main__':
2094 with MyManager() as manager:
2095 maths = manager.Maths()
2096 print(maths.add(4, 3)) # prints 7
2097 print(maths.mul(7, 8)) # prints 56
2098
2099
2100 Using a remote manager
2101 """"""""""""""""""""""
2102
2103 It is possible to run a manager server on one machine and have clients use it
2104 from other machines (assuming that the firewalls involved allow it).
2105
2106 Running the following commands creates a server for a single shared queue which
2107 remote clients can access::
2108
2109 >>> from multiprocessing.managers import BaseManager
2110 >>> from queue import Queue
2111 >>> queue = Queue()
2112 >>> class QueueManager(BaseManager): pass
2113 >>> QueueManager.register('get_queue', callable=lambda:queue)
2114 >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
2115 >>> s = m.get_server()
2116 >>> s.serve_forever()
2117
2118 One client can access the server as follows::
2119
2120 >>> from multiprocessing.managers import BaseManager
2121 >>> class QueueManager(BaseManager): pass
2122 >>> QueueManager.register('get_queue')
2123 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
2124 >>> m.connect()
2125 >>> queue = m.get_queue()
2126 >>> queue.put('hello')
2127
2128 Another client can also use it::
2129
2130 >>> from multiprocessing.managers import BaseManager
2131 >>> class QueueManager(BaseManager): pass
2132 >>> QueueManager.register('get_queue')
2133 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
2134 >>> m.connect()
2135 >>> queue = m.get_queue()
2136 >>> queue.get()
2137 'hello'
2138
2139 Local processes can also access that queue, using the code from above on the
2140 client to access it remotely::
2141
2142 >>> from multiprocessing import Process, Queue
2143 >>> from multiprocessing.managers import BaseManager
2144 >>> class Worker(Process):
2145 ... def __init__(self, q):
2146 ... self.q = q
2147 ... super().__init__()
2148 ... def run(self):
2149 ... self.q.put('local hello')
2150 ...
2151 >>> queue = Queue()
2152 >>> w = Worker(queue)
2153 >>> w.start()
2154 >>> class QueueManager(BaseManager): pass
2155 ...
2156 >>> QueueManager.register('get_queue', callable=lambda: queue)
2157 >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
2158 >>> s = m.get_server()
2159 >>> s.serve_forever()
2160
2161 .. _multiprocessing-proxy_objects:
2162
2163 Proxy Objects
2164 ^^^^^^^^^^^^^
2165
2166 A proxy is an object which *refers* to a shared object which lives (presumably)
2167 in a different process. The shared object is said to be the *referent* of the
2168 proxy. Multiple proxy objects may have the same referent.
2169
2170 A proxy object has methods which invoke corresponding methods of its referent
2171 (although not every method of the referent will necessarily be available through
2172 the proxy). In this way, a proxy can be used just like its referent can:
2173
2174 .. doctest::
2175
2176 >>> mp_context = multiprocessing.get_context('spawn')
2177 >>> manager = mp_context.Manager()
2178 >>> l = manager.list([i*i for i in range(10)])
2179 >>> print(l)
2180 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2181 >>> print(repr(l))
2182 <ListProxy object, typeid 'list' at 0x...>
2183 >>> l[4]
2184 16
2185 >>> l[2:5]
2186 [4, 9, 16]
2187
2188 Notice that applying :func:`str` to a proxy will return the representation of
2189 the referent, whereas applying :func:`repr` will return the representation of
2190 the proxy.
2191
2192 An important feature of proxy objects is that they are picklable so they can be
2193 passed between processes. As such, a referent can contain
2194 :ref:`multiprocessing-proxy_objects`. This permits nesting of these managed
2195 lists, dicts, and other :ref:`multiprocessing-proxy_objects`:
2196
2197 .. doctest::
2198
2199 >>> a = manager.list()
2200 >>> b = manager.list()
2201 >>> a.append(b) # referent of a now contains referent of b
2202 >>> print(a, b)
2203 [<ListProxy object, typeid 'list' at ...>] []
2204 >>> b.append('hello')
2205 >>> print(a[0], b)
2206 ['hello'] ['hello']
2207
2208 Similarly, dict and list proxies may be nested inside one another::
2209
2210 >>> l_outer = manager.list([ manager.dict() for i in range(2) ])
2211 >>> d_first_inner = l_outer[0]
2212 >>> d_first_inner['a'] = 1
2213 >>> d_first_inner['b'] = 2
2214 >>> l_outer[1]['c'] = 3
2215 >>> l_outer[1]['z'] = 26
2216 >>> print(l_outer[0])
2217 {'a': 1, 'b': 2}
2218 >>> print(l_outer[1])
2219 {'c': 3, 'z': 26}
2220
2221 If standard (non-proxy) :class:`list` or :class:`dict` objects are contained
2222 in a referent, modifications to those mutable values will not be propagated
2223 through the manager because the proxy has no way of knowing when the values
2224 contained within are modified. However, storing a value in a container proxy
2225 (which triggers a ``__setitem__`` on the proxy object) does propagate through
2226 the manager and so to effectively modify such an item, one could re-assign the
2227 modified value to the container proxy::
2228
2229 # create a list proxy and append a mutable object (a dictionary)
2230 lproxy = manager.list()
2231 lproxy.append({})
2232 # now mutate the dictionary
2233 d = lproxy[0]
2234 d['a'] = 1
2235 d['b'] = 2
2236 # at this point, the changes to d are not yet synced, but by
2237 # updating the dictionary, the proxy is notified of the change
2238 lproxy[0] = d
2239
2240 This approach is perhaps less convenient than employing nested
2241 :ref:`multiprocessing-proxy_objects` for most use cases but also
2242 demonstrates a level of control over the synchronization.
2243
2244 .. note::
2245
2246 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
2247 by value. So, for instance, we have:
2248
2249 .. doctest::
2250
2251 >>> manager.list([1,2,3]) == [1,2,3]
2252 False
2253
2254 One should just use a copy of the referent instead when making comparisons.
2255
2256 .. class:: BaseProxy
2257
2258 Proxy objects are instances of subclasses of :class:`BaseProxy`.
2259
2260 .. method:: _callmethod(methodname[, args[, kwds]])
2261
2262 Call and return the result of a method of the proxy's referent.
2263
2264 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
2265
2266 proxy._callmethod(methodname, args, kwds)
2267
2268 will evaluate the expression ::
2269
2270 getattr(obj, methodname)(*args, **kwds)
2271
2272 in the manager's process.
2273
2274 The returned value will be a copy of the result of the call or a proxy to
2275 a new shared object -- see documentation for the *method_to_typeid*
2276 argument of :meth:`BaseManager.register`.
2277
2278 If an exception is raised by the call, then is re-raised by
2279 :meth:`_callmethod`. If some other exception is raised in the manager's
2280 process then this is converted into a :exc:`RemoteError` exception and is
2281 raised by :meth:`_callmethod`.
2282
2283 Note in particular that an exception will be raised if *methodname* has
2284 not been *exposed*.
2285
2286 An example of the usage of :meth:`_callmethod`:
2287
2288 .. doctest::
2289
2290 >>> l = manager.list(range(10))
2291 >>> l._callmethod('__len__')
2292 10
2293 >>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
2294 [2, 3, 4, 5, 6]
2295 >>> l._callmethod('__getitem__', (20,)) # equivalent to l[20]
2296 Traceback (most recent call last):
2297 ...
2298 IndexError: list index out of range
2299
2300 .. method:: _getvalue()
2301
2302 Return a copy of the referent.
2303
2304 If the referent is unpicklable then this will raise an exception.
2305
2306 .. method:: __repr__
2307
2308 Return a representation of the proxy object.
2309
2310 .. method:: __str__
2311
2312 Return the representation of the referent.
2313
2314
2315 Cleanup
2316 """""""
2317
2318 A proxy object uses a weakref callback so that when it gets garbage collected it
2319 deregisters itself from the manager which owns its referent.
2320
2321 A shared object gets deleted from the manager process when there are no longer
2322 any proxies referring to it.
2323
2324
2325 Process Pools
2326 ^^^^^^^^^^^^^
2327
2328 .. module:: multiprocessing.pool
2329 :synopsis: Create pools of processes.
2330
2331 One can create a pool of processes which will carry out tasks submitted to it
2332 with the :class:`Pool` class.
2333
2334 .. class:: Pool([processes[, initializer[, initargs[, maxtasksperchild [, context]]]]])
2335
2336 A process pool object which controls a pool of worker processes to which jobs
2337 can be submitted. It supports asynchronous results with timeouts and
2338 callbacks and has a parallel map implementation.
2339
2340 *processes* is the number of worker processes to use. If *processes* is
2341 ``None`` then the number returned by :func:`os.process_cpu_count` is used.
2342
2343 If *initializer* is not ``None`` then each worker process will call
2344 ``initializer(*initargs)`` when it starts.
2345
2346 *maxtasksperchild* is the number of tasks a worker process can complete
2347 before it will exit and be replaced with a fresh worker process, to enable
2348 unused resources to be freed. The default *maxtasksperchild* is ``None``, which
2349 means worker processes will live as long as the pool.
2350
2351 *context* can be used to specify the context used for starting
2352 the worker processes. Usually a pool is created using the
2353 function :func:`multiprocessing.Pool` or the :meth:`Pool` method
2354 of a context object. In both cases *context* is set
2355 appropriately. If ``None``, calling this function will have the side effect
2356 of setting the current global start method if it has not been set already.
2357 See the :func:`get_context` function.
2358
2359 Note that the methods of the pool object should only be called by
2360 the process which created the pool.
2361
2362 .. warning::
2363 :class:`multiprocessing.pool` objects have internal resources that need to be
2364 properly managed (like any other resource) by using the pool as a context manager
2365 or by calling :meth:`close` and :meth:`terminate` manually. Failure to do this
2366 can lead to the process hanging on finalization.
2367
2368 Note that it is **not correct** to rely on the garbage collector to destroy the pool
2369 as CPython does not assure that the finalizer of the pool will be called
2370 (see :meth:`object.__del__` for more information).
2371
2372 .. versionchanged:: 3.2
2373 Added the *maxtasksperchild* parameter.
2374
2375 .. versionchanged:: 3.4
2376 Added the *context* parameter.
2377
2378 .. versionchanged:: 3.13
2379 *processes* uses :func:`os.process_cpu_count` by default, instead of
2380 :func:`os.cpu_count`.
2381
2382 .. note::
2383
2384 Worker processes within a :class:`Pool` typically live for the complete
2385 duration of the Pool's work queue. A frequent pattern found in other
2386 systems (such as Apache, mod_wsgi, etc) to free resources held by
2387 workers is to allow a worker within a pool to complete only a set
2388 amount of work before being exiting, being cleaned up and a new
2389 process spawned to replace the old one. The *maxtasksperchild*
2390 argument to the :class:`Pool` exposes this ability to the end user.
2391
2392 .. method:: apply(func[, args[, kwds]])
2393
2394 Call *func* with arguments *args* and keyword arguments *kwds*. It blocks
2395 until the result is ready. Given this blocks, :meth:`apply_async` is
2396 better suited for performing work in parallel. Additionally, *func*
2397 is only executed in one of the workers of the pool.
2398
2399 .. method:: apply_async(func[, args[, kwds[, callback[, error_callback]]]])
2400
2401 A variant of the :meth:`apply` method which returns a
2402 :class:`~multiprocessing.pool.AsyncResult` object.
2403
2404 If *callback* is specified then it should be a callable which accepts a
2405 single argument. When the result becomes ready *callback* is applied to
2406 it, that is unless the call failed, in which case the *error_callback*
2407 is applied instead.
2408
2409 If *error_callback* is specified then it should be a callable which
2410 accepts a single argument. If the target function fails, then
2411 the *error_callback* is called with the exception instance.
2412
2413 Callbacks should complete immediately since otherwise the thread which
2414 handles the results will get blocked.
2415
2416 .. method:: map(func, iterable[, chunksize])
2417
2418 A parallel equivalent of the :func:`map` built-in function (it supports only
2419 one *iterable* argument though, for multiple iterables see :meth:`starmap`).
2420 It blocks until the result is ready.
2421
2422 This method chops the iterable into a number of chunks which it submits to
2423 the process pool as separate tasks. The (approximate) size of these
2424 chunks can be specified by setting *chunksize* to a positive integer.
2425
2426 Note that it may cause high memory usage for very long iterables. Consider
2427 using :meth:`imap` or :meth:`imap_unordered` with explicit *chunksize*
2428 option for better efficiency.
2429
2430 .. method:: map_async(func, iterable[, chunksize[, callback[, error_callback]]])
2431
2432 A variant of the :meth:`.map` method which returns a
2433 :class:`~multiprocessing.pool.AsyncResult` object.
2434
2435 If *callback* is specified then it should be a callable which accepts a
2436 single argument. When the result becomes ready *callback* is applied to
2437 it, that is unless the call failed, in which case the *error_callback*
2438 is applied instead.
2439
2440 If *error_callback* is specified then it should be a callable which
2441 accepts a single argument. If the target function fails, then
2442 the *error_callback* is called with the exception instance.
2443
2444 Callbacks should complete immediately since otherwise the thread which
2445 handles the results will get blocked.
2446
2447 .. method:: imap(func, iterable[, chunksize])
2448
2449 A lazier version of :meth:`.map`.
2450
2451 The *chunksize* argument is the same as the one used by the :meth:`.map`
2452 method. For very long iterables using a large value for *chunksize* can
2453 make the job complete **much** faster than using the default value of
2454 ``1``.
2455
2456 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
2457 returned by the :meth:`imap` method has an optional *timeout* parameter:
2458 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
2459 result cannot be returned within *timeout* seconds.
2460
2461 .. method:: imap_unordered(func, iterable[, chunksize])
2462
2463 The same as :meth:`imap` except that the ordering of the results from the
2464 returned iterator should be considered arbitrary. (Only when there is
2465 only one worker process is the order guaranteed to be "correct".)
2466
2467 .. method:: starmap(func, iterable[, chunksize])
2468
2469 Like :meth:`~multiprocessing.pool.Pool.map` except that the
2470 elements of the *iterable* are expected to be iterables that are
2471 unpacked as arguments.
2472
2473 Hence an *iterable* of ``[(1,2), (3, 4)]`` results in ``[func(1,2),
2474 func(3,4)]``.
2475
2476 .. versionadded:: 3.3
2477
2478 .. method:: starmap_async(func, iterable[, chunksize[, callback[, error_callback]]])
2479
2480 A combination of :meth:`starmap` and :meth:`map_async` that iterates over
2481 *iterable* of iterables and calls *func* with the iterables unpacked.
2482 Returns a result object.
2483
2484 .. versionadded:: 3.3
2485
2486 .. method:: close()
2487
2488 Prevents any more tasks from being submitted to the pool. Once all the
2489 tasks have been completed the worker processes will exit.
2490
2491 .. method:: terminate()
2492
2493 Stops the worker processes immediately without completing outstanding
2494 work. When the pool object is garbage collected :meth:`terminate` will be
2495 called immediately.
2496
2497 .. method:: join()
2498
2499 Wait for the worker processes to exit. One must call :meth:`close` or
2500 :meth:`terminate` before using :meth:`join`.
2501
2502 .. versionchanged:: 3.3
2503 Pool objects now support the context management protocol -- see
2504 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the
2505 pool object, and :meth:`~contextmanager.__exit__` calls :meth:`terminate`.
2506
2507
2508 .. class:: AsyncResult
2509
2510 The class of the result returned by :meth:`Pool.apply_async` and
2511 :meth:`Pool.map_async`.
2512
2513 .. method:: get([timeout])
2514
2515 Return the result when it arrives. If *timeout* is not ``None`` and the
2516 result does not arrive within *timeout* seconds then
2517 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
2518 an exception then that exception will be reraised by :meth:`get`.
2519
2520 .. method:: wait([timeout])
2521
2522 Wait until the result is available or until *timeout* seconds pass.
2523
2524 .. method:: ready()
2525
2526 Return whether the call has completed.
2527
2528 .. method:: successful()
2529
2530 Return whether the call completed without raising an exception. Will
2531 raise :exc:`ValueError` if the result is not ready.
2532
2533 .. versionchanged:: 3.7
2534 If the result is not ready, :exc:`ValueError` is raised instead of
2535 :exc:`AssertionError`.
2536
2537 The following example demonstrates the use of a pool::
2538
2539 from multiprocessing import Pool
2540 import time
2541
2542 def f(x):
2543 return x*x
2544
2545 if __name__ == '__main__':
2546 with Pool(processes=4) as pool: # start 4 worker processes
2547 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
2548 print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow
2549
2550 print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]"
2551
2552 it = pool.imap(f, range(10))
2553 print(next(it)) # prints "0"
2554 print(next(it)) # prints "1"
2555 print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow
2556
2557 result = pool.apply_async(time.sleep, (10,))
2558 print(result.get(timeout=1)) # raises multiprocessing.TimeoutError
2559
2560
2561 .. _multiprocessing-listeners-clients:
2562
2563 Listeners and Clients
2564 ^^^^^^^^^^^^^^^^^^^^^
2565
2566 .. module:: multiprocessing.connection
2567 :synopsis: API for dealing with sockets.
2568
2569 Usually message passing between processes is done using queues or by using
2570 :class:`~Connection` objects returned by
2571 :func:`~multiprocessing.Pipe`.
2572
2573 However, the :mod:`multiprocessing.connection` module allows some extra
2574 flexibility. It basically gives a high level message oriented API for dealing
2575 with sockets or Windows named pipes. It also has support for *digest
2576 authentication* using the :mod:`hmac` module, and for polling
2577 multiple connections at the same time.
2578
2579
2580 .. function:: deliver_challenge(connection, authkey)
2581
2582 Send a randomly generated message to the other end of the connection and wait
2583 for a reply.
2584
2585 If the reply matches the digest of the message using *authkey* as the key
2586 then a welcome message is sent to the other end of the connection. Otherwise
2587 :exc:`~multiprocessing.AuthenticationError` is raised.
2588
2589 .. function:: answer_challenge(connection, authkey)
2590
2591 Receive a message, calculate the digest of the message using *authkey* as the
2592 key, and then send the digest back.
2593
2594 If a welcome message is not received, then
2595 :exc:`~multiprocessing.AuthenticationError` is raised.
2596
2597 .. function:: Client(address[, family[, authkey]])
2598
2599 Attempt to set up a connection to the listener which is using address
2600 *address*, returning a :class:`~Connection`.
2601
2602 The type of the connection is determined by *family* argument, but this can
2603 generally be omitted since it can usually be inferred from the format of
2604 *address*. (See :ref:`multiprocessing-address-formats`)
2605
2606 If *authkey* is given and not ``None``, it should be a byte string and will be
2607 used as the secret key for an HMAC-based authentication challenge. No
2608 authentication is done if *authkey* is ``None``.
2609 :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails.
2610 See :ref:`multiprocessing-auth-keys`.
2611
2612 .. class:: Listener([address[, family[, backlog[, authkey]]]])
2613
2614 A wrapper for a bound socket or Windows named pipe which is 'listening' for
2615 connections.
2616
2617 *address* is the address to be used by the bound socket or named pipe of the
2618 listener object.
2619
2620 .. note::
2621
2622 If an address of '0.0.0.0' is used, the address will not be a connectable
2623 end point on Windows. If you require a connectable end-point,
2624 you should use '127.0.0.1'.
2625
2626 *family* is the type of socket (or named pipe) to use. This can be one of
2627 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
2628 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
2629 the first is guaranteed to be available. If *family* is ``None`` then the
2630 family is inferred from the format of *address*. If *address* is also
2631 ``None`` then a default is chosen. This default is the family which is
2632 assumed to be the fastest available. See
2633 :ref:`multiprocessing-address-formats`. Note that if *family* is
2634 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
2635 private temporary directory created using :func:`tempfile.mkstemp`.
2636
2637 If the listener object uses a socket then *backlog* (1 by default) is passed
2638 to the :meth:`~socket.socket.listen` method of the socket once it has been
2639 bound.
2640
2641 If *authkey* is given and not ``None``, it should be a byte string and will be
2642 used as the secret key for an HMAC-based authentication challenge. No
2643 authentication is done if *authkey* is ``None``.
2644 :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails.
2645 See :ref:`multiprocessing-auth-keys`.
2646
2647 .. method:: accept()
2648
2649 Accept a connection on the bound socket or named pipe of the listener
2650 object and return a :class:`~Connection` object.
2651 If authentication is attempted and fails, then
2652 :exc:`~multiprocessing.AuthenticationError` is raised.
2653
2654 .. method:: close()
2655
2656 Close the bound socket or named pipe of the listener object. This is
2657 called automatically when the listener is garbage collected. However it
2658 is advisable to call it explicitly.
2659
2660 Listener objects have the following read-only properties:
2661
2662 .. attribute:: address
2663
2664 The address which is being used by the Listener object.
2665
2666 .. attribute:: last_accepted
2667
2668 The address from which the last accepted connection came. If this is
2669 unavailable then it is ``None``.
2670
2671 .. versionchanged:: 3.3
2672 Listener objects now support the context management protocol -- see
2673 :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the
2674 listener object, and :meth:`~contextmanager.__exit__` calls :meth:`close`.
2675
2676 .. function:: wait(object_list, timeout=None)
2677
2678 Wait till an object in *object_list* is ready. Returns the list of
2679 those objects in *object_list* which are ready. If *timeout* is a
2680 float then the call blocks for at most that many seconds. If
2681 *timeout* is ``None`` then it will block for an unlimited period.
2682 A negative timeout is equivalent to a zero timeout.
2683
2684 For both POSIX and Windows, an object can appear in *object_list* if
2685 it is
2686
2687 * a readable :class:`~multiprocessing.connection.Connection` object;
2688 * a connected and readable :class:`socket.socket` object; or
2689 * the :attr:`~multiprocessing.Process.sentinel` attribute of a
2690 :class:`~multiprocessing.Process` object.
2691
2692 A connection or socket object is ready when there is data available
2693 to be read from it, or the other end has been closed.
2694
2695 **POSIX**: ``wait(object_list, timeout)`` almost equivalent
2696 ``select.select(object_list, [], [], timeout)``. The difference is
2697 that, if :func:`select.select` is interrupted by a signal, it can
2698 raise :exc:`OSError` with an error number of ``EINTR``, whereas
2699 :func:`wait` will not.
2700
2701 **Windows**: An item in *object_list* must either be an integer
2702 handle which is waitable (according to the definition used by the
2703 documentation of the Win32 function ``WaitForMultipleObjects()``)
2704 or it can be an object with a :meth:`~io.IOBase.fileno` method which returns a
2705 socket handle or pipe handle. (Note that pipe handles and socket
2706 handles are **not** waitable handles.)
2707
2708 .. versionadded:: 3.3
2709
2710
2711 **Examples**
2712
2713 The following server code creates a listener which uses ``'secret password'`` as
2714 an authentication key. It then waits for a connection and sends some data to
2715 the client::
2716
2717 from multiprocessing.connection import Listener
2718 from array import array
2719
2720 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
2721
2722 with Listener(address, authkey=b'secret password') as listener:
2723 with listener.accept() as conn:
2724 print('connection accepted from', listener.last_accepted)
2725
2726 conn.send([2.25, None, 'junk', float])
2727
2728 conn.send_bytes(b'hello')
2729
2730 conn.send_bytes(array('i', [42, 1729]))
2731
2732 The following code connects to the server and receives some data from the
2733 server::
2734
2735 from multiprocessing.connection import Client
2736 from array import array
2737
2738 address = ('localhost', 6000)
2739
2740 with Client(address, authkey=b'secret password') as conn:
2741 print(conn.recv()) # => [2.25, None, 'junk', float]
2742
2743 print(conn.recv_bytes()) # => 'hello'
2744
2745 arr = array('i', [0, 0, 0, 0, 0])
2746 print(conn.recv_bytes_into(arr)) # => 8
2747 print(arr) # => array('i', [42, 1729, 0, 0, 0])
2748
2749 The following code uses :func:`~multiprocessing.connection.wait` to
2750 wait for messages from multiple processes at once::
2751
2752 from multiprocessing import Process, Pipe, current_process
2753 from multiprocessing.connection import wait
2754
2755 def foo(w):
2756 for i in range(10):
2757 w.send((i, current_process().name))
2758 w.close()
2759
2760 if __name__ == '__main__':
2761 readers = []
2762
2763 for i in range(4):
2764 r, w = Pipe(duplex=False)
2765 readers.append(r)
2766 p = Process(target=foo, args=(w,))
2767 p.start()
2768 # We close the writable end of the pipe now to be sure that
2769 # p is the only process which owns a handle for it. This
2770 # ensures that when p closes its handle for the writable end,
2771 # wait() will promptly report the readable end as being ready.
2772 w.close()
2773
2774 while readers:
2775 for r in wait(readers):
2776 try:
2777 msg = r.recv()
2778 except EOFError:
2779 readers.remove(r)
2780 else:
2781 print(msg)
2782
2783
2784 .. _multiprocessing-address-formats:
2785
2786 Address Formats
2787 """""""""""""""
2788
2789 * An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
2790 *hostname* is a string and *port* is an integer.
2791
2792 * An ``'AF_UNIX'`` address is a string representing a filename on the
2793 filesystem.
2794
2795 * An ``'AF_PIPE'`` address is a string of the form
2796 :samp:`r'\\\\\\.\\pipe\\\\{PipeName}'`. To use :func:`Client` to connect to a named
2797 pipe on a remote computer called *ServerName* one should use an address of the
2798 form :samp:`r'\\\\\\\\{ServerName}\\pipe\\\\{PipeName}'` instead.
2799
2800 Note that any string beginning with two backslashes is assumed by default to be
2801 an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
2802
2803
2804 .. _multiprocessing-auth-keys:
2805
2806 Authentication keys
2807 ^^^^^^^^^^^^^^^^^^^
2808
2809 When one uses :meth:`Connection.recv <Connection.recv>`, the
2810 data received is automatically
2811 unpickled. Unfortunately unpickling data from an untrusted source is a security
2812 risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
2813 to provide digest authentication.
2814
2815 An authentication key is a byte string which can be thought of as a
2816 password: once a connection is established both ends will demand proof
2817 that the other knows the authentication key. (Demonstrating that both
2818 ends are using the same key does **not** involve sending the key over
2819 the connection.)
2820
2821 If authentication is requested but no authentication key is specified then the
2822 return value of ``current_process().authkey`` is used (see
2823 :class:`~multiprocessing.Process`). This value will be automatically inherited by
2824 any :class:`~multiprocessing.Process` object that the current process creates.
2825 This means that (by default) all processes of a multi-process program will share
2826 a single authentication key which can be used when setting up connections
2827 between themselves.
2828
2829 Suitable authentication keys can also be generated by using :func:`os.urandom`.
2830
2831
2832 Logging
2833 ^^^^^^^
2834
2835 Some support for logging is available. Note, however, that the :mod:`logging`
2836 package does not use process shared locks so it is possible (depending on the
2837 handler type) for messages from different processes to get mixed up.
2838
2839 .. currentmodule:: multiprocessing
2840 .. function:: get_logger()
2841
2842 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
2843 will be created.
2844
2845 When first created the logger has level :const:`logging.NOTSET` and no
2846 default handler. Messages sent to this logger will not by default propagate
2847 to the root logger.
2848
2849 Note that on Windows child processes will only inherit the level of the
2850 parent process's logger -- any other customization of the logger will not be
2851 inherited.
2852
2853 .. currentmodule:: multiprocessing
2854 .. function:: log_to_stderr(level=None)
2855
2856 This function performs a call to :func:`get_logger` but in addition to
2857 returning the logger created by get_logger, it adds a handler which sends
2858 output to :data:`sys.stderr` using format
2859 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2860 You can modify ``levelname`` of the logger by passing a ``level`` argument.
2861
2862 Below is an example session with logging turned on::
2863
2864 >>> import multiprocessing, logging
2865 >>> logger = multiprocessing.log_to_stderr()
2866 >>> logger.setLevel(logging.INFO)
2867 >>> logger.warning('doomed')
2868 [WARNING/MainProcess] doomed
2869 >>> m = multiprocessing.Manager()
2870 [INFO/SyncManager-...] child process calling self.run()
2871 [INFO/SyncManager-...] created temp directory /.../pymp-...
2872 [INFO/SyncManager-...] manager serving at '/.../listener-...'
2873 >>> del m
2874 [INFO/MainProcess] sending shutdown message to manager
2875 [INFO/SyncManager-...] manager exiting with exitcode 0
2876
2877 For a full table of logging levels, see the :mod:`logging` module.
2878
2879
2880 The :mod:`multiprocessing.dummy` module
2881 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2882
2883 .. module:: multiprocessing.dummy
2884 :synopsis: Dumb wrapper around threading.
2885
2886 :mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
2887 no more than a wrapper around the :mod:`threading` module.
2888
2889 .. currentmodule:: multiprocessing.pool
2890
2891 In particular, the ``Pool`` function provided by :mod:`multiprocessing.dummy`
2892 returns an instance of :class:`ThreadPool`, which is a subclass of
2893 :class:`Pool` that supports all the same method calls but uses a pool of
2894 worker threads rather than worker processes.
2895
2896
2897 .. class:: ThreadPool([processes[, initializer[, initargs]]])
2898
2899 A thread pool object which controls a pool of worker threads to which jobs
2900 can be submitted. :class:`ThreadPool` instances are fully interface
2901 compatible with :class:`Pool` instances, and their resources must also be
2902 properly managed, either by using the pool as a context manager or by
2903 calling :meth:`~multiprocessing.pool.Pool.close` and
2904 :meth:`~multiprocessing.pool.Pool.terminate` manually.
2905
2906 *processes* is the number of worker threads to use. If *processes* is
2907 ``None`` then the number returned by :func:`os.process_cpu_count` is used.
2908
2909 If *initializer* is not ``None`` then each worker process will call
2910 ``initializer(*initargs)`` when it starts.
2911
2912 Unlike :class:`Pool`, *maxtasksperchild* and *context* cannot be provided.
2913
2914 .. note::
2915
2916 A :class:`ThreadPool` shares the same interface as :class:`Pool`, which
2917 is designed around a pool of processes and predates the introduction of
2918 the :class:`concurrent.futures` module. As such, it inherits some
2919 operations that don't make sense for a pool backed by threads, and it
2920 has its own type for representing the status of asynchronous jobs,
2921 :class:`AsyncResult`, that is not understood by any other libraries.
2922
2923 Users should generally prefer to use
2924 :class:`concurrent.futures.ThreadPoolExecutor`, which has a simpler
2925 interface that was designed around threads from the start, and which
2926 returns :class:`concurrent.futures.Future` instances that are
2927 compatible with many other libraries, including :mod:`asyncio`.
2928
2929
2930 .. _multiprocessing-programming:
2931
2932 Programming guidelines
2933 ----------------------
2934
2935 There are certain guidelines and idioms which should be adhered to when using
2936 :mod:`multiprocessing`.
2937
2938
2939 All start methods
2940 ^^^^^^^^^^^^^^^^^
2941
2942 The following applies to all start methods.
2943
2944 Avoid shared state
2945
2946 As far as possible one should try to avoid shifting large amounts of data
2947 between processes.
2948
2949 It is probably best to stick to using queues or pipes for communication
2950 between processes rather than using the lower level synchronization
2951 primitives.
2952
2953 Picklability
2954
2955 Ensure that the arguments to the methods of proxies are picklable.
2956
2957 Thread safety of proxies
2958
2959 Do not use a proxy object from more than one thread unless you protect it
2960 with a lock.
2961
2962 (There is never a problem with different processes using the *same* proxy.)
2963
2964 Joining zombie processes
2965
2966 On POSIX when a process finishes but has not been joined it becomes a zombie.
2967 There should never be very many because each time a new process starts (or
2968 :func:`~multiprocessing.active_children` is called) all completed processes
2969 which have not yet been joined will be joined. Also calling a finished
2970 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
2971 join the process. Even so it is probably good
2972 practice to explicitly join all the processes that you start.
2973
2974 Better to inherit than pickle/unpickle
2975
2976 When using the *spawn* or *forkserver* start methods many types
2977 from :mod:`multiprocessing` need to be picklable so that child
2978 processes can use them. However, one should generally avoid
2979 sending shared objects to other processes using pipes or queues.
2980 Instead you should arrange the program so that a process which
2981 needs access to a shared resource created elsewhere can inherit it
2982 from an ancestor process.
2983
2984 Avoid terminating processes
2985
2986 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
2987 method to stop a process is liable to
2988 cause any shared resources (such as locks, semaphores, pipes and queues)
2989 currently being used by the process to become broken or unavailable to other
2990 processes.
2991
2992 Therefore it is probably best to only consider using
2993 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
2994 which never use any shared resources.
2995
2996 Joining processes that use queues
2997
2998 Bear in mind that a process that has put items in a queue will wait before
2999 terminating until all the buffered items are fed by the "feeder" thread to
3000 the underlying pipe. (The child process can call the
3001 :meth:`Queue.cancel_join_thread <multiprocessing.Queue.cancel_join_thread>`
3002 method of the queue to avoid this behaviour.)
3003
3004 This means that whenever you use a queue you need to make sure that all
3005 items which have been put on the queue will eventually be removed before the
3006 process is joined. Otherwise you cannot be sure that processes which have
3007 put items on the queue will terminate. Remember also that non-daemonic
3008 processes will be joined automatically.
3009
3010 An example which will deadlock is the following::
3011
3012 from multiprocessing import Process, Queue
3013
3014 def f(q):
3015 q.put('X' * 1000000)
3016
3017 if __name__ == '__main__':
3018 queue = Queue()
3019 p = Process(target=f, args=(queue,))
3020 p.start()
3021 p.join() # this deadlocks
3022 obj = queue.get()
3023
3024 A fix here would be to swap the last two lines (or simply remove the
3025 ``p.join()`` line).
3026
3027 Explicitly pass resources to child processes
3028
3029 On POSIX using the *fork* start method, a child process can make
3030 use of a shared resource created in a parent process using a
3031 global resource. However, it is better to pass the object as an
3032 argument to the constructor for the child process.
3033
3034 Apart from making the code (potentially) compatible with Windows
3035 and the other start methods this also ensures that as long as the
3036 child process is still alive the object will not be garbage
3037 collected in the parent process. This might be important if some
3038 resource is freed when the object is garbage collected in the
3039 parent process.
3040
3041 So for instance ::
3042
3043 from multiprocessing import Process, Lock
3044
3045 def f():
3046 ... do something using "lock" ...
3047
3048 if __name__ == '__main__':
3049 lock = Lock()
3050 for i in range(10):
3051 Process(target=f).start()
3052
3053 should be rewritten as ::
3054
3055 from multiprocessing import Process, Lock
3056
3057 def f(l):
3058 ... do something using "l" ...
3059
3060 if __name__ == '__main__':
3061 lock = Lock()
3062 for i in range(10):
3063 Process(target=f, args=(lock,)).start()
3064
3065 Beware of replacing :data:`sys.stdin` with a "file like object"
3066
3067 :mod:`multiprocessing` originally unconditionally called::
3068
3069 os.close(sys.stdin.fileno())
3070
3071 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
3072 in issues with processes-in-processes. This has been changed to::
3073
3074 sys.stdin.close()
3075 sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)
3076
3077 Which solves the fundamental issue of processes colliding with each other
3078 resulting in a bad file descriptor error, but introduces a potential danger
3079 to applications which replace :func:`sys.stdin` with a "file-like object"
3080 with output buffering. This danger is that if multiple processes call
3081 :meth:`~io.IOBase.close` on this file-like object, it could result in the same
3082 data being flushed to the object multiple times, resulting in corruption.
3083
3084 If you write a file-like object and implement your own caching, you can
3085 make it fork-safe by storing the pid whenever you append to the cache,
3086 and discarding the cache when the pid changes. For example::
3087
3088 @property
3089 def cache(self):
3090 pid = os.getpid()
3091 if pid != self._pid:
3092 self._pid = pid
3093 self._cache = []
3094 return self._cache
3095
3096 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
3097
3098 .. _multiprocessing-programming-spawn:
3099 .. _multiprocessing-programming-forkserver:
3100
3101 The *spawn* and *forkserver* start methods
3102 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3103
3104 There are a few extra restrictions which don't apply to the *fork*
3105 start method.
3106
3107 More picklability
3108
3109 Ensure that all arguments to :class:`~multiprocessing.Process` are
3110 picklable. Also, if you subclass ``Process.__init__``, you must make sure
3111 that instances will be picklable when the
3112 :meth:`Process.start <multiprocessing.Process.start>` method is called.
3113
3114 Global variables
3115
3116 Bear in mind that if code run in a child process tries to access a global
3117 variable, then the value it sees (if any) may not be the same as the value
3118 in the parent process at the time that :meth:`Process.start
3119 <multiprocessing.Process.start>` was called.
3120
3121 However, global variables which are just module level constants cause no
3122 problems.
3123
3124 .. _multiprocessing-safe-main-import:
3125
3126 Safe importing of main module
3127
3128 Make sure that the main module can be safely imported by a new Python
3129 interpreter without causing unintended side effects (such as starting a new
3130 process).
3131
3132 For example, using the *spawn* or *forkserver* start method
3133 running the following module would fail with a
3134 :exc:`RuntimeError`::
3135
3136 from multiprocessing import Process
3137
3138 def foo():
3139 print('hello')
3140
3141 p = Process(target=foo)
3142 p.start()
3143
3144 Instead one should protect the "entry point" of the program by using ``if
3145 __name__ == '__main__':`` as follows::
3146
3147 from multiprocessing import Process, freeze_support, set_start_method
3148
3149 def foo():
3150 print('hello')
3151
3152 if __name__ == '__main__':
3153 freeze_support()
3154 set_start_method('spawn')
3155 p = Process(target=foo)
3156 p.start()
3157
3158 (The ``freeze_support()`` line can be omitted if the program will be run
3159 normally instead of frozen.)
3160
3161 This allows the newly spawned Python interpreter to safely import the module
3162 and then run the module's ``foo()`` function.
3163
3164 Similar restrictions apply if a pool or manager is created in the main
3165 module.
3166
3167
3168 .. _multiprocessing-examples:
3169
3170 Examples
3171 --------
3172
3173 Demonstration of how to create and use customized managers and proxies:
3174
3175 .. literalinclude:: ../includes/mp_newtype.py
3176 :language: python3
3177
3178
3179 Using :class:`~multiprocessing.pool.Pool`:
3180
3181 .. literalinclude:: ../includes/mp_pool.py
3182 :language: python3
3183
3184
3185 An example showing how to use queues to feed tasks to a collection of worker
3186 processes and collect the results:
3187
3188 .. literalinclude:: ../includes/mp_workers.py