17db96d56Sopenharmony_ci:mod:`multiprocessing` --- Process-based parallelism
27db96d56Sopenharmony_ci====================================================
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci.. module:: multiprocessing
57db96d56Sopenharmony_ci   :synopsis: Process-based parallelism.
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_ci**Source code:** :source:`Lib/multiprocessing/`
87db96d56Sopenharmony_ci
97db96d56Sopenharmony_ci--------------
107db96d56Sopenharmony_ci
117db96d56Sopenharmony_ci.. include:: ../includes/wasm-notavail.rst
127db96d56Sopenharmony_ci
137db96d56Sopenharmony_ciIntroduction
147db96d56Sopenharmony_ci------------
157db96d56Sopenharmony_ci
167db96d56Sopenharmony_ci:mod:`multiprocessing` is a package that supports spawning processes using an
177db96d56Sopenharmony_ciAPI similar to the :mod:`threading` module.  The :mod:`multiprocessing` package
187db96d56Sopenharmony_cioffers both local and remote concurrency, effectively side-stepping the
197db96d56Sopenharmony_ci:term:`Global Interpreter Lock <global interpreter lock>` by using
207db96d56Sopenharmony_cisubprocesses instead of threads.  Due
217db96d56Sopenharmony_cito this, the :mod:`multiprocessing` module allows the programmer to fully
227db96d56Sopenharmony_cileverage multiple processors on a given machine.  It runs on both Unix and
237db96d56Sopenharmony_ciWindows.
247db96d56Sopenharmony_ci
257db96d56Sopenharmony_ciThe :mod:`multiprocessing` module also introduces APIs which do not have
267db96d56Sopenharmony_cianalogs in the :mod:`threading` module.  A prime example of this is the
277db96d56Sopenharmony_ci:class:`~multiprocessing.pool.Pool` object which offers a convenient means of
287db96d56Sopenharmony_ciparallelizing the execution of a function across multiple input values,
297db96d56Sopenharmony_cidistributing the input data across processes (data parallelism).  The following
307db96d56Sopenharmony_ciexample demonstrates the common practice of defining such functions in a module
317db96d56Sopenharmony_ciso that child processes can successfully import that module.  This basic example
327db96d56Sopenharmony_ciof data parallelism using :class:`~multiprocessing.pool.Pool`, ::
337db96d56Sopenharmony_ci
347db96d56Sopenharmony_ci   from multiprocessing import Pool
357db96d56Sopenharmony_ci
367db96d56Sopenharmony_ci   def f(x):
377db96d56Sopenharmony_ci       return x*x
387db96d56Sopenharmony_ci
397db96d56Sopenharmony_ci   if __name__ == '__main__':
407db96d56Sopenharmony_ci       with Pool(5) as p:
417db96d56Sopenharmony_ci           print(p.map(f, [1, 2, 3]))
427db96d56Sopenharmony_ci
437db96d56Sopenharmony_ciwill print to standard output ::
447db96d56Sopenharmony_ci
457db96d56Sopenharmony_ci   [1, 4, 9]
467db96d56Sopenharmony_ci
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ci.. seealso::
497db96d56Sopenharmony_ci
507db96d56Sopenharmony_ci   :class:`concurrent.futures.ProcessPoolExecutor` offers a higher level interface
517db96d56Sopenharmony_ci   to push tasks to a background process without blocking execution of the
527db96d56Sopenharmony_ci   calling process. Compared to using the :class:`~multiprocessing.pool.Pool`
537db96d56Sopenharmony_ci   interface directly, the :mod:`concurrent.futures` API more readily allows
547db96d56Sopenharmony_ci   the submission of work to the underlying process pool to be separated from
557db96d56Sopenharmony_ci   waiting for the results.
567db96d56Sopenharmony_ci
577db96d56Sopenharmony_ci
587db96d56Sopenharmony_ciThe :class:`Process` class
597db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ciIn :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
627db96d56Sopenharmony_ciobject and then calling its :meth:`~Process.start` method.  :class:`Process`
637db96d56Sopenharmony_cifollows the API of :class:`threading.Thread`.  A trivial example of a
647db96d56Sopenharmony_cimultiprocess program is ::
657db96d56Sopenharmony_ci
667db96d56Sopenharmony_ci   from multiprocessing import Process
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ci   def f(name):
697db96d56Sopenharmony_ci       print('hello', name)
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ci   if __name__ == '__main__':
727db96d56Sopenharmony_ci       p = Process(target=f, args=('bob',))
737db96d56Sopenharmony_ci       p.start()
747db96d56Sopenharmony_ci       p.join()
757db96d56Sopenharmony_ci
767db96d56Sopenharmony_ciTo show the individual process IDs involved, here is an expanded example::
777db96d56Sopenharmony_ci
787db96d56Sopenharmony_ci    from multiprocessing import Process
797db96d56Sopenharmony_ci    import os
807db96d56Sopenharmony_ci
817db96d56Sopenharmony_ci    def info(title):
827db96d56Sopenharmony_ci        print(title)
837db96d56Sopenharmony_ci        print('module name:', __name__)
847db96d56Sopenharmony_ci        print('parent process:', os.getppid())
857db96d56Sopenharmony_ci        print('process id:', os.getpid())
867db96d56Sopenharmony_ci
877db96d56Sopenharmony_ci    def f(name):
887db96d56Sopenharmony_ci        info('function f')
897db96d56Sopenharmony_ci        print('hello', name)
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ci    if __name__ == '__main__':
927db96d56Sopenharmony_ci        info('main line')
937db96d56Sopenharmony_ci        p = Process(target=f, args=('bob',))
947db96d56Sopenharmony_ci        p.start()
957db96d56Sopenharmony_ci        p.join()
967db96d56Sopenharmony_ci
977db96d56Sopenharmony_ciFor an explanation of why the ``if __name__ == '__main__'`` part is
987db96d56Sopenharmony_cinecessary, see :ref:`multiprocessing-programming`.
997db96d56Sopenharmony_ci
1007db96d56Sopenharmony_ci
1017db96d56Sopenharmony_ci
1027db96d56Sopenharmony_ciContexts and start methods
1037db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~
1047db96d56Sopenharmony_ci
1057db96d56Sopenharmony_ci.. _multiprocessing-start-methods:
1067db96d56Sopenharmony_ci
1077db96d56Sopenharmony_ciDepending on the platform, :mod:`multiprocessing` supports three ways
1087db96d56Sopenharmony_cito start a process.  These *start methods* are
1097db96d56Sopenharmony_ci
1107db96d56Sopenharmony_ci  *spawn*
1117db96d56Sopenharmony_ci    The parent process starts a fresh Python interpreter process.  The
1127db96d56Sopenharmony_ci    child process will only inherit those resources necessary to run
1137db96d56Sopenharmony_ci    the process object's :meth:`~Process.run` method.  In particular,
1147db96d56Sopenharmony_ci    unnecessary file descriptors and handles from the parent process
1157db96d56Sopenharmony_ci    will not be inherited.  Starting a process using this method is
1167db96d56Sopenharmony_ci    rather slow compared to using *fork* or *forkserver*.
1177db96d56Sopenharmony_ci
1187db96d56Sopenharmony_ci    Available on Unix and Windows.  The default on Windows and macOS.
1197db96d56Sopenharmony_ci
1207db96d56Sopenharmony_ci  *fork*
1217db96d56Sopenharmony_ci    The parent process uses :func:`os.fork` to fork the Python
1227db96d56Sopenharmony_ci    interpreter.  The child process, when it begins, is effectively
1237db96d56Sopenharmony_ci    identical to the parent process.  All resources of the parent are
1247db96d56Sopenharmony_ci    inherited by the child process.  Note that safely forking a
1257db96d56Sopenharmony_ci    multithreaded process is problematic.
1267db96d56Sopenharmony_ci
1277db96d56Sopenharmony_ci    Available on Unix only.  The default on Unix.
1287db96d56Sopenharmony_ci
1297db96d56Sopenharmony_ci  *forkserver*
1307db96d56Sopenharmony_ci    When the program starts and selects the *forkserver* start method,
1317db96d56Sopenharmony_ci    a server process is started.  From then on, whenever a new process
1327db96d56Sopenharmony_ci    is needed, the parent process connects to the server and requests
1337db96d56Sopenharmony_ci    that it fork a new process.  The fork server process is single
1347db96d56Sopenharmony_ci    threaded so it is safe for it to use :func:`os.fork`.  No
1357db96d56Sopenharmony_ci    unnecessary resources are inherited.
1367db96d56Sopenharmony_ci
1377db96d56Sopenharmony_ci    Available on Unix platforms which support passing file descriptors
1387db96d56Sopenharmony_ci    over Unix pipes.
1397db96d56Sopenharmony_ci
1407db96d56Sopenharmony_ci.. versionchanged:: 3.8
1417db96d56Sopenharmony_ci
1427db96d56Sopenharmony_ci   On macOS, the *spawn* start method is now the default.  The *fork* start
1437db96d56Sopenharmony_ci   method should be considered unsafe as it can lead to crashes of the
1447db96d56Sopenharmony_ci   subprocess. See :issue:`33725`.
1457db96d56Sopenharmony_ci
1467db96d56Sopenharmony_ci.. versionchanged:: 3.4
1477db96d56Sopenharmony_ci   *spawn* added on all Unix platforms, and *forkserver* added for
1487db96d56Sopenharmony_ci   some Unix platforms.
1497db96d56Sopenharmony_ci   Child processes no longer inherit all of the parents inheritable
1507db96d56Sopenharmony_ci   handles on Windows.
1517db96d56Sopenharmony_ci
1527db96d56Sopenharmony_ciOn Unix using the *spawn* or *forkserver* start methods will also
1537db96d56Sopenharmony_cistart a *resource tracker* process which tracks the unlinked named
1547db96d56Sopenharmony_cisystem resources (such as named semaphores or
1557db96d56Sopenharmony_ci:class:`~multiprocessing.shared_memory.SharedMemory` objects) created
1567db96d56Sopenharmony_ciby processes of the program.  When all processes
1577db96d56Sopenharmony_cihave exited the resource tracker unlinks any remaining tracked object.
1587db96d56Sopenharmony_ciUsually there should be none, but if a process was killed by a signal
1597db96d56Sopenharmony_cithere may be some "leaked" resources.  (Neither leaked semaphores nor shared
1607db96d56Sopenharmony_cimemory segments will be automatically unlinked until the next reboot. This is
1617db96d56Sopenharmony_ciproblematic for both objects because the system allows only a limited number of
1627db96d56Sopenharmony_cinamed semaphores, and shared memory segments occupy some space in the main
1637db96d56Sopenharmony_cimemory.)
1647db96d56Sopenharmony_ci
1657db96d56Sopenharmony_ciTo select a start method you use the :func:`set_start_method` in
1667db96d56Sopenharmony_cithe ``if __name__ == '__main__'`` clause of the main module.  For
1677db96d56Sopenharmony_ciexample::
1687db96d56Sopenharmony_ci
1697db96d56Sopenharmony_ci       import multiprocessing as mp
1707db96d56Sopenharmony_ci
1717db96d56Sopenharmony_ci       def foo(q):
1727db96d56Sopenharmony_ci           q.put('hello')
1737db96d56Sopenharmony_ci
1747db96d56Sopenharmony_ci       if __name__ == '__main__':
1757db96d56Sopenharmony_ci           mp.set_start_method('spawn')
1767db96d56Sopenharmony_ci           q = mp.Queue()
1777db96d56Sopenharmony_ci           p = mp.Process(target=foo, args=(q,))
1787db96d56Sopenharmony_ci           p.start()
1797db96d56Sopenharmony_ci           print(q.get())
1807db96d56Sopenharmony_ci           p.join()
1817db96d56Sopenharmony_ci
1827db96d56Sopenharmony_ci:func:`set_start_method` should not be used more than once in the
1837db96d56Sopenharmony_ciprogram.
1847db96d56Sopenharmony_ci
1857db96d56Sopenharmony_ciAlternatively, you can use :func:`get_context` to obtain a context
1867db96d56Sopenharmony_ciobject.  Context objects have the same API as the multiprocessing
1877db96d56Sopenharmony_cimodule, and allow one to use multiple start methods in the same
1887db96d56Sopenharmony_ciprogram. ::
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ci       import multiprocessing as mp
1917db96d56Sopenharmony_ci
1927db96d56Sopenharmony_ci       def foo(q):
1937db96d56Sopenharmony_ci           q.put('hello')
1947db96d56Sopenharmony_ci
1957db96d56Sopenharmony_ci       if __name__ == '__main__':
1967db96d56Sopenharmony_ci           ctx = mp.get_context('spawn')
1977db96d56Sopenharmony_ci           q = ctx.Queue()
1987db96d56Sopenharmony_ci           p = ctx.Process(target=foo, args=(q,))
1997db96d56Sopenharmony_ci           p.start()
2007db96d56Sopenharmony_ci           print(q.get())
2017db96d56Sopenharmony_ci           p.join()
2027db96d56Sopenharmony_ci
2037db96d56Sopenharmony_ciNote that objects related to one context may not be compatible with
2047db96d56Sopenharmony_ciprocesses for a different context.  In particular, locks created using
2057db96d56Sopenharmony_cithe *fork* context cannot be passed to processes started using the
2067db96d56Sopenharmony_ci*spawn* or *forkserver* start methods.
2077db96d56Sopenharmony_ci
2087db96d56Sopenharmony_ciA library which wants to use a particular start method should probably
2097db96d56Sopenharmony_ciuse :func:`get_context` to avoid interfering with the choice of the
2107db96d56Sopenharmony_cilibrary user.
2117db96d56Sopenharmony_ci
2127db96d56Sopenharmony_ci.. warning::
2137db96d56Sopenharmony_ci
2147db96d56Sopenharmony_ci   The ``'spawn'`` and ``'forkserver'`` start methods cannot currently
2157db96d56Sopenharmony_ci   be used with "frozen" executables (i.e., binaries produced by
2167db96d56Sopenharmony_ci   packages like **PyInstaller** and **cx_Freeze**) on Unix.
2177db96d56Sopenharmony_ci   The ``'fork'`` start method does work.
2187db96d56Sopenharmony_ci
2197db96d56Sopenharmony_ci
2207db96d56Sopenharmony_ciExchanging objects between processes
2217db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ci:mod:`multiprocessing` supports two types of communication channel between
2247db96d56Sopenharmony_ciprocesses:
2257db96d56Sopenharmony_ci
2267db96d56Sopenharmony_ci**Queues**
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ci   The :class:`Queue` class is a near clone of :class:`queue.Queue`.  For
2297db96d56Sopenharmony_ci   example::
2307db96d56Sopenharmony_ci
2317db96d56Sopenharmony_ci      from multiprocessing import Process, Queue
2327db96d56Sopenharmony_ci
2337db96d56Sopenharmony_ci      def f(q):
2347db96d56Sopenharmony_ci          q.put([42, None, 'hello'])
2357db96d56Sopenharmony_ci
2367db96d56Sopenharmony_ci      if __name__ == '__main__':
2377db96d56Sopenharmony_ci          q = Queue()
2387db96d56Sopenharmony_ci          p = Process(target=f, args=(q,))
2397db96d56Sopenharmony_ci          p.start()
2407db96d56Sopenharmony_ci          print(q.get())    # prints "[42, None, 'hello']"
2417db96d56Sopenharmony_ci          p.join()
2427db96d56Sopenharmony_ci
2437db96d56Sopenharmony_ci   Queues are thread and process safe.
2447db96d56Sopenharmony_ci
2457db96d56Sopenharmony_ci**Pipes**
2467db96d56Sopenharmony_ci
2477db96d56Sopenharmony_ci   The :func:`Pipe` function returns a pair of connection objects connected by a
2487db96d56Sopenharmony_ci   pipe which by default is duplex (two-way).  For example::
2497db96d56Sopenharmony_ci
2507db96d56Sopenharmony_ci      from multiprocessing import Process, Pipe
2517db96d56Sopenharmony_ci
2527db96d56Sopenharmony_ci      def f(conn):
2537db96d56Sopenharmony_ci          conn.send([42, None, 'hello'])
2547db96d56Sopenharmony_ci          conn.close()
2557db96d56Sopenharmony_ci
2567db96d56Sopenharmony_ci      if __name__ == '__main__':
2577db96d56Sopenharmony_ci          parent_conn, child_conn = Pipe()
2587db96d56Sopenharmony_ci          p = Process(target=f, args=(child_conn,))
2597db96d56Sopenharmony_ci          p.start()
2607db96d56Sopenharmony_ci          print(parent_conn.recv())   # prints "[42, None, 'hello']"
2617db96d56Sopenharmony_ci          p.join()
2627db96d56Sopenharmony_ci
2637db96d56Sopenharmony_ci   The two connection objects returned by :func:`Pipe` represent the two ends of
2647db96d56Sopenharmony_ci   the pipe.  Each connection object has :meth:`~Connection.send` and
2657db96d56Sopenharmony_ci   :meth:`~Connection.recv` methods (among others).  Note that data in a pipe
2667db96d56Sopenharmony_ci   may become corrupted if two processes (or threads) try to read from or write
2677db96d56Sopenharmony_ci   to the *same* end of the pipe at the same time.  Of course there is no risk
2687db96d56Sopenharmony_ci   of corruption from processes using different ends of the pipe at the same
2697db96d56Sopenharmony_ci   time.
2707db96d56Sopenharmony_ci
2717db96d56Sopenharmony_ci
2727db96d56Sopenharmony_ciSynchronization between processes
2737db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2747db96d56Sopenharmony_ci
2757db96d56Sopenharmony_ci:mod:`multiprocessing` contains equivalents of all the synchronization
2767db96d56Sopenharmony_ciprimitives from :mod:`threading`.  For instance one can use a lock to ensure
2777db96d56Sopenharmony_cithat only one process prints to standard output at a time::
2787db96d56Sopenharmony_ci
2797db96d56Sopenharmony_ci   from multiprocessing import Process, Lock
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ci   def f(l, i):
2827db96d56Sopenharmony_ci       l.acquire()
2837db96d56Sopenharmony_ci       try:
2847db96d56Sopenharmony_ci           print('hello world', i)
2857db96d56Sopenharmony_ci       finally:
2867db96d56Sopenharmony_ci           l.release()
2877db96d56Sopenharmony_ci
2887db96d56Sopenharmony_ci   if __name__ == '__main__':
2897db96d56Sopenharmony_ci       lock = Lock()
2907db96d56Sopenharmony_ci
2917db96d56Sopenharmony_ci       for num in range(10):
2927db96d56Sopenharmony_ci           Process(target=f, args=(lock, num)).start()
2937db96d56Sopenharmony_ci
2947db96d56Sopenharmony_ciWithout using the lock output from the different processes is liable to get all
2957db96d56Sopenharmony_cimixed up.
2967db96d56Sopenharmony_ci
2977db96d56Sopenharmony_ci
2987db96d56Sopenharmony_ciSharing state between processes
2997db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3007db96d56Sopenharmony_ci
3017db96d56Sopenharmony_ciAs mentioned above, when doing concurrent programming it is usually best to
3027db96d56Sopenharmony_ciavoid using shared state as far as possible.  This is particularly true when
3037db96d56Sopenharmony_ciusing multiple processes.
3047db96d56Sopenharmony_ci
3057db96d56Sopenharmony_ciHowever, if you really do need to use some shared data then
3067db96d56Sopenharmony_ci:mod:`multiprocessing` provides a couple of ways of doing so.
3077db96d56Sopenharmony_ci
3087db96d56Sopenharmony_ci**Shared memory**
3097db96d56Sopenharmony_ci
3107db96d56Sopenharmony_ci   Data can be stored in a shared memory map using :class:`Value` or
3117db96d56Sopenharmony_ci   :class:`Array`.  For example, the following code ::
3127db96d56Sopenharmony_ci
3137db96d56Sopenharmony_ci      from multiprocessing import Process, Value, Array
3147db96d56Sopenharmony_ci
3157db96d56Sopenharmony_ci      def f(n, a):
3167db96d56Sopenharmony_ci          n.value = 3.1415927
3177db96d56Sopenharmony_ci          for i in range(len(a)):
3187db96d56Sopenharmony_ci              a[i] = -a[i]
3197db96d56Sopenharmony_ci
3207db96d56Sopenharmony_ci      if __name__ == '__main__':
3217db96d56Sopenharmony_ci          num = Value('d', 0.0)
3227db96d56Sopenharmony_ci          arr = Array('i', range(10))
3237db96d56Sopenharmony_ci
3247db96d56Sopenharmony_ci          p = Process(target=f, args=(num, arr))
3257db96d56Sopenharmony_ci          p.start()
3267db96d56Sopenharmony_ci          p.join()
3277db96d56Sopenharmony_ci
3287db96d56Sopenharmony_ci          print(num.value)
3297db96d56Sopenharmony_ci          print(arr[:])
3307db96d56Sopenharmony_ci
3317db96d56Sopenharmony_ci   will print ::
3327db96d56Sopenharmony_ci
3337db96d56Sopenharmony_ci      3.1415927
3347db96d56Sopenharmony_ci      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
3357db96d56Sopenharmony_ci
3367db96d56Sopenharmony_ci   The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
3377db96d56Sopenharmony_ci   typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
3387db96d56Sopenharmony_ci   double precision float and ``'i'`` indicates a signed integer.  These shared
3397db96d56Sopenharmony_ci   objects will be process and thread-safe.
3407db96d56Sopenharmony_ci
3417db96d56Sopenharmony_ci   For more flexibility in using shared memory one can use the
3427db96d56Sopenharmony_ci   :mod:`multiprocessing.sharedctypes` module which supports the creation of
3437db96d56Sopenharmony_ci   arbitrary ctypes objects allocated from shared memory.
3447db96d56Sopenharmony_ci
3457db96d56Sopenharmony_ci**Server process**
3467db96d56Sopenharmony_ci
3477db96d56Sopenharmony_ci   A manager object returned by :func:`Manager` controls a server process which
3487db96d56Sopenharmony_ci   holds Python objects and allows other processes to manipulate them using
3497db96d56Sopenharmony_ci   proxies.
3507db96d56Sopenharmony_ci
3517db96d56Sopenharmony_ci   A manager returned by :func:`Manager` will support types
3527db96d56Sopenharmony_ci   :class:`list`, :class:`dict`, :class:`~managers.Namespace`, :class:`Lock`,
3537db96d56Sopenharmony_ci   :class:`RLock`, :class:`Semaphore`, :class:`BoundedSemaphore`,
3547db96d56Sopenharmony_ci   :class:`Condition`, :class:`Event`, :class:`Barrier`,
3557db96d56Sopenharmony_ci   :class:`Queue`, :class:`Value` and :class:`Array`.  For example, ::
3567db96d56Sopenharmony_ci
3577db96d56Sopenharmony_ci      from multiprocessing import Process, Manager
3587db96d56Sopenharmony_ci
3597db96d56Sopenharmony_ci      def f(d, l):
3607db96d56Sopenharmony_ci          d[1] = '1'
3617db96d56Sopenharmony_ci          d['2'] = 2
3627db96d56Sopenharmony_ci          d[0.25] = None
3637db96d56Sopenharmony_ci          l.reverse()
3647db96d56Sopenharmony_ci
3657db96d56Sopenharmony_ci      if __name__ == '__main__':
3667db96d56Sopenharmony_ci          with Manager() as manager:
3677db96d56Sopenharmony_ci              d = manager.dict()
3687db96d56Sopenharmony_ci              l = manager.list(range(10))
3697db96d56Sopenharmony_ci
3707db96d56Sopenharmony_ci              p = Process(target=f, args=(d, l))
3717db96d56Sopenharmony_ci              p.start()
3727db96d56Sopenharmony_ci              p.join()
3737db96d56Sopenharmony_ci
3747db96d56Sopenharmony_ci              print(d)
3757db96d56Sopenharmony_ci              print(l)
3767db96d56Sopenharmony_ci
3777db96d56Sopenharmony_ci   will print ::
3787db96d56Sopenharmony_ci
3797db96d56Sopenharmony_ci       {0.25: None, 1: '1', '2': 2}
3807db96d56Sopenharmony_ci       [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
3817db96d56Sopenharmony_ci
3827db96d56Sopenharmony_ci   Server process managers are more flexible than using shared memory objects
3837db96d56Sopenharmony_ci   because they can be made to support arbitrary object types.  Also, a single
3847db96d56Sopenharmony_ci   manager can be shared by processes on different computers over a network.
3857db96d56Sopenharmony_ci   They are, however, slower than using shared memory.
3867db96d56Sopenharmony_ci
3877db96d56Sopenharmony_ci
3887db96d56Sopenharmony_ciUsing a pool of workers
3897db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~
3907db96d56Sopenharmony_ci
3917db96d56Sopenharmony_ciThe :class:`~multiprocessing.pool.Pool` class represents a pool of worker
3927db96d56Sopenharmony_ciprocesses.  It has methods which allows tasks to be offloaded to the worker
3937db96d56Sopenharmony_ciprocesses in a few different ways.
3947db96d56Sopenharmony_ci
3957db96d56Sopenharmony_ciFor example::
3967db96d56Sopenharmony_ci
3977db96d56Sopenharmony_ci   from multiprocessing import Pool, TimeoutError
3987db96d56Sopenharmony_ci   import time
3997db96d56Sopenharmony_ci   import os
4007db96d56Sopenharmony_ci
4017db96d56Sopenharmony_ci   def f(x):
4027db96d56Sopenharmony_ci       return x*x
4037db96d56Sopenharmony_ci
4047db96d56Sopenharmony_ci   if __name__ == '__main__':
4057db96d56Sopenharmony_ci       # start 4 worker processes
4067db96d56Sopenharmony_ci       with Pool(processes=4) as pool:
4077db96d56Sopenharmony_ci
4087db96d56Sopenharmony_ci           # print "[0, 1, 4,..., 81]"
4097db96d56Sopenharmony_ci           print(pool.map(f, range(10)))
4107db96d56Sopenharmony_ci
4117db96d56Sopenharmony_ci           # print same numbers in arbitrary order
4127db96d56Sopenharmony_ci           for i in pool.imap_unordered(f, range(10)):
4137db96d56Sopenharmony_ci               print(i)
4147db96d56Sopenharmony_ci
4157db96d56Sopenharmony_ci           # evaluate "f(20)" asynchronously
4167db96d56Sopenharmony_ci           res = pool.apply_async(f, (20,))      # runs in *only* one process
4177db96d56Sopenharmony_ci           print(res.get(timeout=1))             # prints "400"
4187db96d56Sopenharmony_ci
4197db96d56Sopenharmony_ci           # evaluate "os.getpid()" asynchronously
4207db96d56Sopenharmony_ci           res = pool.apply_async(os.getpid, ()) # runs in *only* one process
4217db96d56Sopenharmony_ci           print(res.get(timeout=1))             # prints the PID of that process
4227db96d56Sopenharmony_ci
4237db96d56Sopenharmony_ci           # launching multiple evaluations asynchronously *may* use more processes
4247db96d56Sopenharmony_ci           multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
4257db96d56Sopenharmony_ci           print([res.get(timeout=1) for res in multiple_results])
4267db96d56Sopenharmony_ci
4277db96d56Sopenharmony_ci           # make a single worker sleep for 10 seconds
4287db96d56Sopenharmony_ci           res = pool.apply_async(time.sleep, (10,))
4297db96d56Sopenharmony_ci           try:
4307db96d56Sopenharmony_ci               print(res.get(timeout=1))
4317db96d56Sopenharmony_ci           except TimeoutError:
4327db96d56Sopenharmony_ci               print("We lacked patience and got a multiprocessing.TimeoutError")
4337db96d56Sopenharmony_ci
4347db96d56Sopenharmony_ci           print("For the moment, the pool remains available for more work")
4357db96d56Sopenharmony_ci
4367db96d56Sopenharmony_ci       # exiting the 'with'-block has stopped the pool
4377db96d56Sopenharmony_ci       print("Now the pool is closed and no longer available")
4387db96d56Sopenharmony_ci
4397db96d56Sopenharmony_ciNote that the methods of a pool should only ever be used by the
4407db96d56Sopenharmony_ciprocess which created it.
4417db96d56Sopenharmony_ci
4427db96d56Sopenharmony_ci.. note::
4437db96d56Sopenharmony_ci
4447db96d56Sopenharmony_ci   Functionality within this package requires that the ``__main__`` module be
4457db96d56Sopenharmony_ci   importable by the children. This is covered in :ref:`multiprocessing-programming`
4467db96d56Sopenharmony_ci   however it is worth pointing out here. This means that some examples, such
4477db96d56Sopenharmony_ci   as the :class:`multiprocessing.pool.Pool` examples will not work in the
4487db96d56Sopenharmony_ci   interactive interpreter. For example::
4497db96d56Sopenharmony_ci
4507db96d56Sopenharmony_ci      >>> from multiprocessing import Pool
4517db96d56Sopenharmony_ci      >>> p = Pool(5)
4527db96d56Sopenharmony_ci      >>> def f(x):
4537db96d56Sopenharmony_ci      ...     return x*x
4547db96d56Sopenharmony_ci      ...
4557db96d56Sopenharmony_ci      >>> with p:
4567db96d56Sopenharmony_ci      ...   p.map(f, [1,2,3])
4577db96d56Sopenharmony_ci      Process PoolWorker-1:
4587db96d56Sopenharmony_ci      Process PoolWorker-2:
4597db96d56Sopenharmony_ci      Process PoolWorker-3:
4607db96d56Sopenharmony_ci      Traceback (most recent call last):
4617db96d56Sopenharmony_ci      Traceback (most recent call last):
4627db96d56Sopenharmony_ci      Traceback (most recent call last):
4637db96d56Sopenharmony_ci      AttributeError: 'module' object has no attribute 'f'
4647db96d56Sopenharmony_ci      AttributeError: 'module' object has no attribute 'f'
4657db96d56Sopenharmony_ci      AttributeError: 'module' object has no attribute 'f'
4667db96d56Sopenharmony_ci
4677db96d56Sopenharmony_ci   (If you try this it will actually output three full tracebacks
4687db96d56Sopenharmony_ci   interleaved in a semi-random fashion, and then you may have to
4697db96d56Sopenharmony_ci   stop the parent process somehow.)
4707db96d56Sopenharmony_ci
4717db96d56Sopenharmony_ci
4727db96d56Sopenharmony_ciReference
4737db96d56Sopenharmony_ci---------
4747db96d56Sopenharmony_ci
4757db96d56Sopenharmony_ciThe :mod:`multiprocessing` package mostly replicates the API of the
4767db96d56Sopenharmony_ci:mod:`threading` module.
4777db96d56Sopenharmony_ci
4787db96d56Sopenharmony_ci
4797db96d56Sopenharmony_ci:class:`Process` and exceptions
4807db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4817db96d56Sopenharmony_ci
4827db96d56Sopenharmony_ci.. class:: Process(group=None, target=None, name=None, args=(), kwargs={}, \
4837db96d56Sopenharmony_ci                   *, daemon=None)
4847db96d56Sopenharmony_ci
4857db96d56Sopenharmony_ci   Process objects represent activity that is run in a separate process. The
4867db96d56Sopenharmony_ci   :class:`Process` class has equivalents of all the methods of
4877db96d56Sopenharmony_ci   :class:`threading.Thread`.
4887db96d56Sopenharmony_ci
4897db96d56Sopenharmony_ci   The constructor should always be called with keyword arguments. *group*
4907db96d56Sopenharmony_ci   should always be ``None``; it exists solely for compatibility with
4917db96d56Sopenharmony_ci   :class:`threading.Thread`.  *target* is the callable object to be invoked by
4927db96d56Sopenharmony_ci   the :meth:`run()` method.  It defaults to ``None``, meaning nothing is
4937db96d56Sopenharmony_ci   called. *name* is the process name (see :attr:`name` for more details).
4947db96d56Sopenharmony_ci   *args* is the argument tuple for the target invocation.  *kwargs* is a
4957db96d56Sopenharmony_ci   dictionary of keyword arguments for the target invocation.  If provided,
4967db96d56Sopenharmony_ci   the keyword-only *daemon* argument sets the process :attr:`daemon` flag
4977db96d56Sopenharmony_ci   to ``True`` or ``False``.  If ``None`` (the default), this flag will be
4987db96d56Sopenharmony_ci   inherited from the creating process.
4997db96d56Sopenharmony_ci
5007db96d56Sopenharmony_ci   By default, no arguments are passed to *target*. The *args* argument,
5017db96d56Sopenharmony_ci   which defaults to ``()``, can be used to specify a list or tuple of the arguments
5027db96d56Sopenharmony_ci   to pass to *target*.
5037db96d56Sopenharmony_ci
5047db96d56Sopenharmony_ci   If a subclass overrides the constructor, it must make sure it invokes the
5057db96d56Sopenharmony_ci   base class constructor (:meth:`Process.__init__`) before doing anything else
5067db96d56Sopenharmony_ci   to the process.
5077db96d56Sopenharmony_ci
5087db96d56Sopenharmony_ci   .. versionchanged:: 3.3
5097db96d56Sopenharmony_ci      Added the *daemon* argument.
5107db96d56Sopenharmony_ci
5117db96d56Sopenharmony_ci   .. method:: run()
5127db96d56Sopenharmony_ci
5137db96d56Sopenharmony_ci      Method representing the process's activity.
5147db96d56Sopenharmony_ci
5157db96d56Sopenharmony_ci      You may override this method in a subclass.  The standard :meth:`run`
5167db96d56Sopenharmony_ci      method invokes the callable object passed to the object's constructor as
5177db96d56Sopenharmony_ci      the target argument, if any, with sequential and keyword arguments taken
5187db96d56Sopenharmony_ci      from the *args* and *kwargs* arguments, respectively.
5197db96d56Sopenharmony_ci
5207db96d56Sopenharmony_ci      Using a list or tuple as the *args* argument passed to :class:`Process`
5217db96d56Sopenharmony_ci      achieves the same effect.
5227db96d56Sopenharmony_ci
5237db96d56Sopenharmony_ci      Example::
5247db96d56Sopenharmony_ci
5257db96d56Sopenharmony_ci         >>> from multiprocessing import Process
5267db96d56Sopenharmony_ci         >>> p = Process(target=print, args=[1])
5277db96d56Sopenharmony_ci         >>> p.run()
5287db96d56Sopenharmony_ci         1
5297db96d56Sopenharmony_ci         >>> p = Process(target=print, args=(1,))
5307db96d56Sopenharmony_ci         >>> p.run()
5317db96d56Sopenharmony_ci         1
5327db96d56Sopenharmony_ci
5337db96d56Sopenharmony_ci   .. method:: start()
5347db96d56Sopenharmony_ci
5357db96d56Sopenharmony_ci      Start the process's activity.
5367db96d56Sopenharmony_ci
5377db96d56Sopenharmony_ci      This must be called at most once per process object.  It arranges for the
5387db96d56Sopenharmony_ci      object's :meth:`run` method to be invoked in a separate process.
5397db96d56Sopenharmony_ci
5407db96d56Sopenharmony_ci   .. method:: join([timeout])
5417db96d56Sopenharmony_ci
5427db96d56Sopenharmony_ci      If the optional argument *timeout* is ``None`` (the default), the method
5437db96d56Sopenharmony_ci      blocks until the process whose :meth:`join` method is called terminates.
5447db96d56Sopenharmony_ci      If *timeout* is a positive number, it blocks at most *timeout* seconds.
5457db96d56Sopenharmony_ci      Note that the method returns ``None`` if its process terminates or if the
5467db96d56Sopenharmony_ci      method times out.  Check the process's :attr:`exitcode` to determine if
5477db96d56Sopenharmony_ci      it terminated.
5487db96d56Sopenharmony_ci
5497db96d56Sopenharmony_ci      A process can be joined many times.
5507db96d56Sopenharmony_ci
5517db96d56Sopenharmony_ci      A process cannot join itself because this would cause a deadlock.  It is
5527db96d56Sopenharmony_ci      an error to attempt to join a process before it has been started.
5537db96d56Sopenharmony_ci
5547db96d56Sopenharmony_ci   .. attribute:: name
5557db96d56Sopenharmony_ci
5567db96d56Sopenharmony_ci      The process's name.  The name is a string used for identification purposes
5577db96d56Sopenharmony_ci      only.  It has no semantics.  Multiple processes may be given the same
5587db96d56Sopenharmony_ci      name.
5597db96d56Sopenharmony_ci
5607db96d56Sopenharmony_ci      The initial name is set by the constructor.  If no explicit name is
5617db96d56Sopenharmony_ci      provided to the constructor, a name of the form
5627db96d56Sopenharmony_ci      'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' is constructed, where
5637db96d56Sopenharmony_ci      each N\ :sub:`k` is the N-th child of its parent.
5647db96d56Sopenharmony_ci
5657db96d56Sopenharmony_ci   .. method:: is_alive
5667db96d56Sopenharmony_ci
5677db96d56Sopenharmony_ci      Return whether the process is alive.
5687db96d56Sopenharmony_ci
5697db96d56Sopenharmony_ci      Roughly, a process object is alive from the moment the :meth:`start`
5707db96d56Sopenharmony_ci      method returns until the child process terminates.
5717db96d56Sopenharmony_ci
5727db96d56Sopenharmony_ci   .. attribute:: daemon
5737db96d56Sopenharmony_ci
5747db96d56Sopenharmony_ci      The process's daemon flag, a Boolean value.  This must be set before
5757db96d56Sopenharmony_ci      :meth:`start` is called.
5767db96d56Sopenharmony_ci
5777db96d56Sopenharmony_ci      The initial value is inherited from the creating process.
5787db96d56Sopenharmony_ci
5797db96d56Sopenharmony_ci      When a process exits, it attempts to terminate all of its daemonic child
5807db96d56Sopenharmony_ci      processes.
5817db96d56Sopenharmony_ci
5827db96d56Sopenharmony_ci      Note that a daemonic process is not allowed to create child processes.
5837db96d56Sopenharmony_ci      Otherwise a daemonic process would leave its children orphaned if it gets
5847db96d56Sopenharmony_ci      terminated when its parent process exits. Additionally, these are **not**
5857db96d56Sopenharmony_ci      Unix daemons or services, they are normal processes that will be
5867db96d56Sopenharmony_ci      terminated (and not joined) if non-daemonic processes have exited.
5877db96d56Sopenharmony_ci
5887db96d56Sopenharmony_ci   In addition to the  :class:`threading.Thread` API, :class:`Process` objects
5897db96d56Sopenharmony_ci   also support the following attributes and methods:
5907db96d56Sopenharmony_ci
5917db96d56Sopenharmony_ci   .. attribute:: pid
5927db96d56Sopenharmony_ci
5937db96d56Sopenharmony_ci      Return the process ID.  Before the process is spawned, this will be
5947db96d56Sopenharmony_ci      ``None``.
5957db96d56Sopenharmony_ci
5967db96d56Sopenharmony_ci   .. attribute:: exitcode
5977db96d56Sopenharmony_ci
5987db96d56Sopenharmony_ci      The child's exit code.  This will be ``None`` if the process has not yet
5997db96d56Sopenharmony_ci      terminated.
6007db96d56Sopenharmony_ci
6017db96d56Sopenharmony_ci      If the child's :meth:`run` method returned normally, the exit code
6027db96d56Sopenharmony_ci      will be 0.  If it terminated via :func:`sys.exit` with an integer
6037db96d56Sopenharmony_ci      argument *N*, the exit code will be *N*.
6047db96d56Sopenharmony_ci
6057db96d56Sopenharmony_ci      If the child terminated due to an exception not caught within
6067db96d56Sopenharmony_ci      :meth:`run`, the exit code will be 1.  If it was terminated by
6077db96d56Sopenharmony_ci      signal *N*, the exit code will be the negative value *-N*.
6087db96d56Sopenharmony_ci
6097db96d56Sopenharmony_ci   .. attribute:: authkey
6107db96d56Sopenharmony_ci
6117db96d56Sopenharmony_ci      The process's authentication key (a byte string).
6127db96d56Sopenharmony_ci
6137db96d56Sopenharmony_ci      When :mod:`multiprocessing` is initialized the main process is assigned a
6147db96d56Sopenharmony_ci      random string using :func:`os.urandom`.
6157db96d56Sopenharmony_ci
6167db96d56Sopenharmony_ci      When a :class:`Process` object is created, it will inherit the
6177db96d56Sopenharmony_ci      authentication key of its parent process, although this may be changed by
6187db96d56Sopenharmony_ci      setting :attr:`authkey` to another byte string.
6197db96d56Sopenharmony_ci
6207db96d56Sopenharmony_ci      See :ref:`multiprocessing-auth-keys`.
6217db96d56Sopenharmony_ci
6227db96d56Sopenharmony_ci   .. attribute:: sentinel
6237db96d56Sopenharmony_ci
6247db96d56Sopenharmony_ci      A numeric handle of a system object which will become "ready" when
6257db96d56Sopenharmony_ci      the process ends.
6267db96d56Sopenharmony_ci
6277db96d56Sopenharmony_ci      You can use this value if you want to wait on several events at
6287db96d56Sopenharmony_ci      once using :func:`multiprocessing.connection.wait`.  Otherwise
6297db96d56Sopenharmony_ci      calling :meth:`join()` is simpler.
6307db96d56Sopenharmony_ci
6317db96d56Sopenharmony_ci      On Windows, this is an OS handle usable with the ``WaitForSingleObject``
6327db96d56Sopenharmony_ci      and ``WaitForMultipleObjects`` family of API calls.  On Unix, this is
6337db96d56Sopenharmony_ci      a file descriptor usable with primitives from the :mod:`select` module.
6347db96d56Sopenharmony_ci
6357db96d56Sopenharmony_ci      .. versionadded:: 3.3
6367db96d56Sopenharmony_ci
6377db96d56Sopenharmony_ci   .. method:: terminate()
6387db96d56Sopenharmony_ci
6397db96d56Sopenharmony_ci      Terminate the process.  On Unix this is done using the ``SIGTERM`` signal;
6407db96d56Sopenharmony_ci      on Windows :c:func:`TerminateProcess` is used.  Note that exit handlers and
6417db96d56Sopenharmony_ci      finally clauses, etc., will not be executed.
6427db96d56Sopenharmony_ci
6437db96d56Sopenharmony_ci      Note that descendant processes of the process will *not* be terminated --
6447db96d56Sopenharmony_ci      they will simply become orphaned.
6457db96d56Sopenharmony_ci
6467db96d56Sopenharmony_ci      .. warning::
6477db96d56Sopenharmony_ci
6487db96d56Sopenharmony_ci         If this method is used when the associated process is using a pipe or
6497db96d56Sopenharmony_ci         queue then the pipe or queue is liable to become corrupted and may
6507db96d56Sopenharmony_ci         become unusable by other process.  Similarly, if the process has
6517db96d56Sopenharmony_ci         acquired a lock or semaphore etc. then terminating it is liable to
6527db96d56Sopenharmony_ci         cause other processes to deadlock.
6537db96d56Sopenharmony_ci
6547db96d56Sopenharmony_ci   .. method:: kill()
6557db96d56Sopenharmony_ci
6567db96d56Sopenharmony_ci      Same as :meth:`terminate()` but using the ``SIGKILL`` signal on Unix.
6577db96d56Sopenharmony_ci
6587db96d56Sopenharmony_ci      .. versionadded:: 3.7
6597db96d56Sopenharmony_ci
6607db96d56Sopenharmony_ci   .. method:: close()
6617db96d56Sopenharmony_ci
6627db96d56Sopenharmony_ci      Close the :class:`Process` object, releasing all resources associated
6637db96d56Sopenharmony_ci      with it.  :exc:`ValueError` is raised if the underlying process
6647db96d56Sopenharmony_ci      is still running.  Once :meth:`close` returns successfully, most
6657db96d56Sopenharmony_ci      other methods and attributes of the :class:`Process` object will
6667db96d56Sopenharmony_ci      raise :exc:`ValueError`.
6677db96d56Sopenharmony_ci
6687db96d56Sopenharmony_ci      .. versionadded:: 3.7
6697db96d56Sopenharmony_ci
6707db96d56Sopenharmony_ci   Note that the :meth:`start`, :meth:`join`, :meth:`is_alive`,
6717db96d56Sopenharmony_ci   :meth:`terminate` and :attr:`exitcode` methods should only be called by
6727db96d56Sopenharmony_ci   the process that created the process object.
6737db96d56Sopenharmony_ci
6747db96d56Sopenharmony_ci   Example usage of some of the methods of :class:`Process`:
6757db96d56Sopenharmony_ci
6767db96d56Sopenharmony_ci   .. doctest::
6777db96d56Sopenharmony_ci
6787db96d56Sopenharmony_ci       >>> import multiprocessing, time, signal
6797db96d56Sopenharmony_ci       >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
6807db96d56Sopenharmony_ci       >>> print(p, p.is_alive())
6817db96d56Sopenharmony_ci       <Process ... initial> False
6827db96d56Sopenharmony_ci       >>> p.start()
6837db96d56Sopenharmony_ci       >>> print(p, p.is_alive())
6847db96d56Sopenharmony_ci       <Process ... started> True
6857db96d56Sopenharmony_ci       >>> p.terminate()
6867db96d56Sopenharmony_ci       >>> time.sleep(0.1)
6877db96d56Sopenharmony_ci       >>> print(p, p.is_alive())
6887db96d56Sopenharmony_ci       <Process ... stopped exitcode=-SIGTERM> False
6897db96d56Sopenharmony_ci       >>> p.exitcode == -signal.SIGTERM
6907db96d56Sopenharmony_ci       True
6917db96d56Sopenharmony_ci
6927db96d56Sopenharmony_ci.. exception:: ProcessError
6937db96d56Sopenharmony_ci
6947db96d56Sopenharmony_ci   The base class of all :mod:`multiprocessing` exceptions.
6957db96d56Sopenharmony_ci
6967db96d56Sopenharmony_ci.. exception:: BufferTooShort
6977db96d56Sopenharmony_ci
6987db96d56Sopenharmony_ci   Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
6997db96d56Sopenharmony_ci   buffer object is too small for the message read.
7007db96d56Sopenharmony_ci
7017db96d56Sopenharmony_ci   If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
7027db96d56Sopenharmony_ci   the message as a byte string.
7037db96d56Sopenharmony_ci
7047db96d56Sopenharmony_ci.. exception:: AuthenticationError
7057db96d56Sopenharmony_ci
7067db96d56Sopenharmony_ci   Raised when there is an authentication error.
7077db96d56Sopenharmony_ci
7087db96d56Sopenharmony_ci.. exception:: TimeoutError
7097db96d56Sopenharmony_ci
7107db96d56Sopenharmony_ci   Raised by methods with a timeout when the timeout expires.
7117db96d56Sopenharmony_ci
7127db96d56Sopenharmony_ciPipes and Queues
7137db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~
7147db96d56Sopenharmony_ci
7157db96d56Sopenharmony_ciWhen using multiple processes, one generally uses message passing for
7167db96d56Sopenharmony_cicommunication between processes and avoids having to use any synchronization
7177db96d56Sopenharmony_ciprimitives like locks.
7187db96d56Sopenharmony_ci
7197db96d56Sopenharmony_ciFor passing messages one can use :func:`Pipe` (for a connection between two
7207db96d56Sopenharmony_ciprocesses) or a queue (which allows multiple producers and consumers).
7217db96d56Sopenharmony_ci
7227db96d56Sopenharmony_ciThe :class:`Queue`, :class:`SimpleQueue` and :class:`JoinableQueue` types
7237db96d56Sopenharmony_ciare multi-producer, multi-consumer :abbr:`FIFO (first-in, first-out)`
7247db96d56Sopenharmony_ciqueues modelled on the :class:`queue.Queue` class in the
7257db96d56Sopenharmony_cistandard library.  They differ in that :class:`Queue` lacks the
7267db96d56Sopenharmony_ci:meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join` methods introduced
7277db96d56Sopenharmony_ciinto Python 2.5's :class:`queue.Queue` class.
7287db96d56Sopenharmony_ci
7297db96d56Sopenharmony_ciIf you use :class:`JoinableQueue` then you **must** call
7307db96d56Sopenharmony_ci:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
7317db96d56Sopenharmony_cisemaphore used to count the number of unfinished tasks may eventually overflow,
7327db96d56Sopenharmony_ciraising an exception.
7337db96d56Sopenharmony_ci
7347db96d56Sopenharmony_ciNote that one can also create a shared queue by using a manager object -- see
7357db96d56Sopenharmony_ci:ref:`multiprocessing-managers`.
7367db96d56Sopenharmony_ci
7377db96d56Sopenharmony_ci.. note::
7387db96d56Sopenharmony_ci
7397db96d56Sopenharmony_ci   :mod:`multiprocessing` uses the usual :exc:`queue.Empty` and
7407db96d56Sopenharmony_ci   :exc:`queue.Full` exceptions to signal a timeout.  They are not available in
7417db96d56Sopenharmony_ci   the :mod:`multiprocessing` namespace so you need to import them from
7427db96d56Sopenharmony_ci   :mod:`queue`.
7437db96d56Sopenharmony_ci
7447db96d56Sopenharmony_ci.. note::
7457db96d56Sopenharmony_ci
7467db96d56Sopenharmony_ci   When an object is put on a queue, the object is pickled and a
7477db96d56Sopenharmony_ci   background thread later flushes the pickled data to an underlying
7487db96d56Sopenharmony_ci   pipe.  This has some consequences which are a little surprising,
7497db96d56Sopenharmony_ci   but should not cause any practical difficulties -- if they really
7507db96d56Sopenharmony_ci   bother you then you can instead use a queue created with a
7517db96d56Sopenharmony_ci   :ref:`manager <multiprocessing-managers>`.
7527db96d56Sopenharmony_ci
7537db96d56Sopenharmony_ci   (1) After putting an object on an empty queue there may be an
7547db96d56Sopenharmony_ci       infinitesimal delay before the queue's :meth:`~Queue.empty`
7557db96d56Sopenharmony_ci       method returns :const:`False` and :meth:`~Queue.get_nowait` can
7567db96d56Sopenharmony_ci       return without raising :exc:`queue.Empty`.
7577db96d56Sopenharmony_ci
7587db96d56Sopenharmony_ci   (2) If multiple processes are enqueuing objects, it is possible for
7597db96d56Sopenharmony_ci       the objects to be received at the other end out-of-order.
7607db96d56Sopenharmony_ci       However, objects enqueued by the same process will always be in
7617db96d56Sopenharmony_ci       the expected order with respect to each other.
7627db96d56Sopenharmony_ci
7637db96d56Sopenharmony_ci.. warning::
7647db96d56Sopenharmony_ci
7657db96d56Sopenharmony_ci   If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
7667db96d56Sopenharmony_ci   while it is trying to use a :class:`Queue`, then the data in the queue is
7677db96d56Sopenharmony_ci   likely to become corrupted.  This may cause any other process to get an
7687db96d56Sopenharmony_ci   exception when it tries to use the queue later on.
7697db96d56Sopenharmony_ci
7707db96d56Sopenharmony_ci.. warning::
7717db96d56Sopenharmony_ci
7727db96d56Sopenharmony_ci   As mentioned above, if a child process has put items on a queue (and it has
7737db96d56Sopenharmony_ci   not used :meth:`JoinableQueue.cancel_join_thread
7747db96d56Sopenharmony_ci   <multiprocessing.Queue.cancel_join_thread>`), then that process will
7757db96d56Sopenharmony_ci   not terminate until all buffered items have been flushed to the pipe.
7767db96d56Sopenharmony_ci
7777db96d56Sopenharmony_ci   This means that if you try joining that process you may get a deadlock unless
7787db96d56Sopenharmony_ci   you are sure that all items which have been put on the queue have been
7797db96d56Sopenharmony_ci   consumed.  Similarly, if the child process is non-daemonic then the parent
7807db96d56Sopenharmony_ci   process may hang on exit when it tries to join all its non-daemonic children.
7817db96d56Sopenharmony_ci
7827db96d56Sopenharmony_ci   Note that a queue created using a manager does not have this issue.  See
7837db96d56Sopenharmony_ci   :ref:`multiprocessing-programming`.
7847db96d56Sopenharmony_ci
7857db96d56Sopenharmony_ciFor an example of the usage of queues for interprocess communication see
7867db96d56Sopenharmony_ci:ref:`multiprocessing-examples`.
7877db96d56Sopenharmony_ci
7887db96d56Sopenharmony_ci
7897db96d56Sopenharmony_ci.. function:: Pipe([duplex])
7907db96d56Sopenharmony_ci
7917db96d56Sopenharmony_ci   Returns a pair ``(conn1, conn2)`` of
7927db96d56Sopenharmony_ci   :class:`~multiprocessing.connection.Connection` objects representing the
7937db96d56Sopenharmony_ci   ends of a pipe.
7947db96d56Sopenharmony_ci
7957db96d56Sopenharmony_ci   If *duplex* is ``True`` (the default) then the pipe is bidirectional.  If
7967db96d56Sopenharmony_ci   *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
7977db96d56Sopenharmony_ci   used for receiving messages and ``conn2`` can only be used for sending
7987db96d56Sopenharmony_ci   messages.
7997db96d56Sopenharmony_ci
8007db96d56Sopenharmony_ci
8017db96d56Sopenharmony_ci.. class:: Queue([maxsize])
8027db96d56Sopenharmony_ci
8037db96d56Sopenharmony_ci   Returns a process shared queue implemented using a pipe and a few
8047db96d56Sopenharmony_ci   locks/semaphores.  When a process first puts an item on the queue a feeder
8057db96d56Sopenharmony_ci   thread is started which transfers objects from a buffer into the pipe.
8067db96d56Sopenharmony_ci
8077db96d56Sopenharmony_ci   The usual :exc:`queue.Empty` and :exc:`queue.Full` exceptions from the
8087db96d56Sopenharmony_ci   standard library's :mod:`queue` module are raised to signal timeouts.
8097db96d56Sopenharmony_ci
8107db96d56Sopenharmony_ci   :class:`Queue` implements all the methods of :class:`queue.Queue` except for
8117db96d56Sopenharmony_ci   :meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join`.
8127db96d56Sopenharmony_ci
8137db96d56Sopenharmony_ci   .. method:: qsize()
8147db96d56Sopenharmony_ci
8157db96d56Sopenharmony_ci      Return the approximate size of the queue.  Because of
8167db96d56Sopenharmony_ci      multithreading/multiprocessing semantics, this number is not reliable.
8177db96d56Sopenharmony_ci
8187db96d56Sopenharmony_ci      Note that this may raise :exc:`NotImplementedError` on Unix platforms like
8197db96d56Sopenharmony_ci      macOS where ``sem_getvalue()`` is not implemented.
8207db96d56Sopenharmony_ci
8217db96d56Sopenharmony_ci   .. method:: empty()
8227db96d56Sopenharmony_ci
8237db96d56Sopenharmony_ci      Return ``True`` if the queue is empty, ``False`` otherwise.  Because of
8247db96d56Sopenharmony_ci      multithreading/multiprocessing semantics, this is not reliable.
8257db96d56Sopenharmony_ci
8267db96d56Sopenharmony_ci   .. method:: full()
8277db96d56Sopenharmony_ci
8287db96d56Sopenharmony_ci      Return ``True`` if the queue is full, ``False`` otherwise.  Because of
8297db96d56Sopenharmony_ci      multithreading/multiprocessing semantics, this is not reliable.
8307db96d56Sopenharmony_ci
8317db96d56Sopenharmony_ci   .. method:: put(obj[, block[, timeout]])
8327db96d56Sopenharmony_ci
8337db96d56Sopenharmony_ci      Put obj into the queue.  If the optional argument *block* is ``True``
8347db96d56Sopenharmony_ci      (the default) and *timeout* is ``None`` (the default), block if necessary until
8357db96d56Sopenharmony_ci      a free slot is available.  If *timeout* is a positive number, it blocks at
8367db96d56Sopenharmony_ci      most *timeout* seconds and raises the :exc:`queue.Full` exception if no
8377db96d56Sopenharmony_ci      free slot was available within that time.  Otherwise (*block* is
8387db96d56Sopenharmony_ci      ``False``), put an item on the queue if a free slot is immediately
8397db96d56Sopenharmony_ci      available, else raise the :exc:`queue.Full` exception (*timeout* is
8407db96d56Sopenharmony_ci      ignored in that case).
8417db96d56Sopenharmony_ci
8427db96d56Sopenharmony_ci      .. versionchanged:: 3.8
8437db96d56Sopenharmony_ci         If the queue is closed, :exc:`ValueError` is raised instead of
8447db96d56Sopenharmony_ci         :exc:`AssertionError`.
8457db96d56Sopenharmony_ci
8467db96d56Sopenharmony_ci   .. method:: put_nowait(obj)
8477db96d56Sopenharmony_ci
8487db96d56Sopenharmony_ci      Equivalent to ``put(obj, False)``.
8497db96d56Sopenharmony_ci
8507db96d56Sopenharmony_ci   .. method:: get([block[, timeout]])
8517db96d56Sopenharmony_ci
8527db96d56Sopenharmony_ci      Remove and return an item from the queue.  If optional args *block* is
8537db96d56Sopenharmony_ci      ``True`` (the default) and *timeout* is ``None`` (the default), block if
8547db96d56Sopenharmony_ci      necessary until an item is available.  If *timeout* is a positive number,
8557db96d56Sopenharmony_ci      it blocks at most *timeout* seconds and raises the :exc:`queue.Empty`
8567db96d56Sopenharmony_ci      exception if no item was available within that time.  Otherwise (block is
8577db96d56Sopenharmony_ci      ``False``), return an item if one is immediately available, else raise the
8587db96d56Sopenharmony_ci      :exc:`queue.Empty` exception (*timeout* is ignored in that case).
8597db96d56Sopenharmony_ci
8607db96d56Sopenharmony_ci      .. versionchanged:: 3.8
8617db96d56Sopenharmony_ci         If the queue is closed, :exc:`ValueError` is raised instead of
8627db96d56Sopenharmony_ci         :exc:`OSError`.
8637db96d56Sopenharmony_ci
8647db96d56Sopenharmony_ci   .. method:: get_nowait()
8657db96d56Sopenharmony_ci
8667db96d56Sopenharmony_ci      Equivalent to ``get(False)``.
8677db96d56Sopenharmony_ci
8687db96d56Sopenharmony_ci   :class:`multiprocessing.Queue` has a few additional methods not found in
8697db96d56Sopenharmony_ci   :class:`queue.Queue`.  These methods are usually unnecessary for most
8707db96d56Sopenharmony_ci   code:
8717db96d56Sopenharmony_ci
8727db96d56Sopenharmony_ci   .. method:: close()
8737db96d56Sopenharmony_ci
8747db96d56Sopenharmony_ci      Indicate that no more data will be put on this queue by the current
8757db96d56Sopenharmony_ci      process.  The background thread will quit once it has flushed all buffered
8767db96d56Sopenharmony_ci      data to the pipe.  This is called automatically when the queue is garbage
8777db96d56Sopenharmony_ci      collected.
8787db96d56Sopenharmony_ci
8797db96d56Sopenharmony_ci   .. method:: join_thread()
8807db96d56Sopenharmony_ci
8817db96d56Sopenharmony_ci      Join the background thread.  This can only be used after :meth:`close` has
8827db96d56Sopenharmony_ci      been called.  It blocks until the background thread exits, ensuring that
8837db96d56Sopenharmony_ci      all data in the buffer has been flushed to the pipe.
8847db96d56Sopenharmony_ci
8857db96d56Sopenharmony_ci      By default if a process is not the creator of the queue then on exit it
8867db96d56Sopenharmony_ci      will attempt to join the queue's background thread.  The process can call
8877db96d56Sopenharmony_ci      :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
8887db96d56Sopenharmony_ci
8897db96d56Sopenharmony_ci   .. method:: cancel_join_thread()
8907db96d56Sopenharmony_ci
8917db96d56Sopenharmony_ci      Prevent :meth:`join_thread` from blocking.  In particular, this prevents
8927db96d56Sopenharmony_ci      the background thread from being joined automatically when the process
8937db96d56Sopenharmony_ci      exits -- see :meth:`join_thread`.
8947db96d56Sopenharmony_ci
8957db96d56Sopenharmony_ci      A better name for this method might be
8967db96d56Sopenharmony_ci      ``allow_exit_without_flush()``.  It is likely to cause enqueued
8977db96d56Sopenharmony_ci      data to be lost, and you almost certainly will not need to use it.
8987db96d56Sopenharmony_ci      It is really only there if you need the current process to exit
8997db96d56Sopenharmony_ci      immediately without waiting to flush enqueued data to the
9007db96d56Sopenharmony_ci      underlying pipe, and you don't care about lost data.
9017db96d56Sopenharmony_ci
9027db96d56Sopenharmony_ci   .. note::
9037db96d56Sopenharmony_ci
9047db96d56Sopenharmony_ci      This class's functionality requires a functioning shared semaphore
9057db96d56Sopenharmony_ci      implementation on the host operating system. Without one, the
9067db96d56Sopenharmony_ci      functionality in this class will be disabled, and attempts to
9077db96d56Sopenharmony_ci      instantiate a :class:`Queue` will result in an :exc:`ImportError`. See
9087db96d56Sopenharmony_ci      :issue:`3770` for additional information.  The same holds true for any
9097db96d56Sopenharmony_ci      of the specialized queue types listed below.
9107db96d56Sopenharmony_ci
9117db96d56Sopenharmony_ci.. class:: SimpleQueue()
9127db96d56Sopenharmony_ci
9137db96d56Sopenharmony_ci   It is a simplified :class:`Queue` type, very close to a locked :class:`Pipe`.
9147db96d56Sopenharmony_ci
9157db96d56Sopenharmony_ci   .. method:: close()
9167db96d56Sopenharmony_ci
9177db96d56Sopenharmony_ci      Close the queue: release internal resources.
9187db96d56Sopenharmony_ci
9197db96d56Sopenharmony_ci      A queue must not be used anymore after it is closed. For example,
9207db96d56Sopenharmony_ci      :meth:`get`, :meth:`put` and :meth:`empty` methods must no longer be
9217db96d56Sopenharmony_ci      called.
9227db96d56Sopenharmony_ci
9237db96d56Sopenharmony_ci      .. versionadded:: 3.9
9247db96d56Sopenharmony_ci
9257db96d56Sopenharmony_ci   .. method:: empty()
9267db96d56Sopenharmony_ci
9277db96d56Sopenharmony_ci      Return ``True`` if the queue is empty, ``False`` otherwise.
9287db96d56Sopenharmony_ci
9297db96d56Sopenharmony_ci   .. method:: get()
9307db96d56Sopenharmony_ci
9317db96d56Sopenharmony_ci      Remove and return an item from the queue.
9327db96d56Sopenharmony_ci
9337db96d56Sopenharmony_ci   .. method:: put(item)
9347db96d56Sopenharmony_ci
9357db96d56Sopenharmony_ci      Put *item* into the queue.
9367db96d56Sopenharmony_ci
9377db96d56Sopenharmony_ci
9387db96d56Sopenharmony_ci.. class:: JoinableQueue([maxsize])
9397db96d56Sopenharmony_ci
9407db96d56Sopenharmony_ci   :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which
9417db96d56Sopenharmony_ci   additionally has :meth:`task_done` and :meth:`join` methods.
9427db96d56Sopenharmony_ci
9437db96d56Sopenharmony_ci   .. method:: task_done()
9447db96d56Sopenharmony_ci
9457db96d56Sopenharmony_ci      Indicate that a formerly enqueued task is complete. Used by queue
9467db96d56Sopenharmony_ci      consumers.  For each :meth:`~Queue.get` used to fetch a task, a subsequent
9477db96d56Sopenharmony_ci      call to :meth:`task_done` tells the queue that the processing on the task
9487db96d56Sopenharmony_ci      is complete.
9497db96d56Sopenharmony_ci
9507db96d56Sopenharmony_ci      If a :meth:`~queue.Queue.join` is currently blocking, it will resume when all
9517db96d56Sopenharmony_ci      items have been processed (meaning that a :meth:`task_done` call was
9527db96d56Sopenharmony_ci      received for every item that had been :meth:`~Queue.put` into the queue).
9537db96d56Sopenharmony_ci
9547db96d56Sopenharmony_ci      Raises a :exc:`ValueError` if called more times than there were items
9557db96d56Sopenharmony_ci      placed in the queue.
9567db96d56Sopenharmony_ci
9577db96d56Sopenharmony_ci
9587db96d56Sopenharmony_ci   .. method:: join()
9597db96d56Sopenharmony_ci
9607db96d56Sopenharmony_ci      Block until all items in the queue have been gotten and processed.
9617db96d56Sopenharmony_ci
9627db96d56Sopenharmony_ci      The count of unfinished tasks goes up whenever an item is added to the
9637db96d56Sopenharmony_ci      queue.  The count goes down whenever a consumer calls
9647db96d56Sopenharmony_ci      :meth:`task_done` to indicate that the item was retrieved and all work on
9657db96d56Sopenharmony_ci      it is complete.  When the count of unfinished tasks drops to zero,
9667db96d56Sopenharmony_ci      :meth:`~queue.Queue.join` unblocks.
9677db96d56Sopenharmony_ci
9687db96d56Sopenharmony_ci
9697db96d56Sopenharmony_ciMiscellaneous
9707db96d56Sopenharmony_ci~~~~~~~~~~~~~
9717db96d56Sopenharmony_ci
9727db96d56Sopenharmony_ci.. function:: active_children()
9737db96d56Sopenharmony_ci
9747db96d56Sopenharmony_ci   Return list of all live children of the current process.
9757db96d56Sopenharmony_ci
9767db96d56Sopenharmony_ci   Calling this has the side effect of "joining" any processes which have
9777db96d56Sopenharmony_ci   already finished.
9787db96d56Sopenharmony_ci
9797db96d56Sopenharmony_ci.. function:: cpu_count()
9807db96d56Sopenharmony_ci
9817db96d56Sopenharmony_ci   Return the number of CPUs in the system.
9827db96d56Sopenharmony_ci
9837db96d56Sopenharmony_ci   This number is not equivalent to the number of CPUs the current process can
9847db96d56Sopenharmony_ci   use.  The number of usable CPUs can be obtained with
9857db96d56Sopenharmony_ci   ``len(os.sched_getaffinity(0))``
9867db96d56Sopenharmony_ci
9877db96d56Sopenharmony_ci   When the number of CPUs cannot be determined a :exc:`NotImplementedError`
9887db96d56Sopenharmony_ci   is raised.
9897db96d56Sopenharmony_ci
9907db96d56Sopenharmony_ci   .. seealso::
9917db96d56Sopenharmony_ci      :func:`os.cpu_count`
9927db96d56Sopenharmony_ci
9937db96d56Sopenharmony_ci.. function:: current_process()
9947db96d56Sopenharmony_ci
9957db96d56Sopenharmony_ci   Return the :class:`Process` object corresponding to the current process.
9967db96d56Sopenharmony_ci
9977db96d56Sopenharmony_ci   An analogue of :func:`threading.current_thread`.
9987db96d56Sopenharmony_ci
9997db96d56Sopenharmony_ci.. function:: parent_process()
10007db96d56Sopenharmony_ci
10017db96d56Sopenharmony_ci   Return the :class:`Process` object corresponding to the parent process of
10027db96d56Sopenharmony_ci   the :func:`current_process`. For the main process, ``parent_process`` will
10037db96d56Sopenharmony_ci   be ``None``.
10047db96d56Sopenharmony_ci
10057db96d56Sopenharmony_ci   .. versionadded:: 3.8
10067db96d56Sopenharmony_ci
10077db96d56Sopenharmony_ci.. function:: freeze_support()
10087db96d56Sopenharmony_ci
10097db96d56Sopenharmony_ci   Add support for when a program which uses :mod:`multiprocessing` has been
10107db96d56Sopenharmony_ci   frozen to produce a Windows executable.  (Has been tested with **py2exe**,
10117db96d56Sopenharmony_ci   **PyInstaller** and **cx_Freeze**.)
10127db96d56Sopenharmony_ci
10137db96d56Sopenharmony_ci   One needs to call this function straight after the ``if __name__ ==
10147db96d56Sopenharmony_ci   '__main__'`` line of the main module.  For example::
10157db96d56Sopenharmony_ci
10167db96d56Sopenharmony_ci      from multiprocessing import Process, freeze_support
10177db96d56Sopenharmony_ci
10187db96d56Sopenharmony_ci      def f():
10197db96d56Sopenharmony_ci          print('hello world!')
10207db96d56Sopenharmony_ci
10217db96d56Sopenharmony_ci      if __name__ == '__main__':
10227db96d56Sopenharmony_ci          freeze_support()
10237db96d56Sopenharmony_ci          Process(target=f).start()
10247db96d56Sopenharmony_ci
10257db96d56Sopenharmony_ci   If the ``freeze_support()`` line is omitted then trying to run the frozen
10267db96d56Sopenharmony_ci   executable will raise :exc:`RuntimeError`.
10277db96d56Sopenharmony_ci
10287db96d56Sopenharmony_ci   Calling ``freeze_support()`` has no effect when invoked on any operating
10297db96d56Sopenharmony_ci   system other than Windows.  In addition, if the module is being run
10307db96d56Sopenharmony_ci   normally by the Python interpreter on Windows (the program has not been
10317db96d56Sopenharmony_ci   frozen), then ``freeze_support()`` has no effect.
10327db96d56Sopenharmony_ci
10337db96d56Sopenharmony_ci.. function:: get_all_start_methods()
10347db96d56Sopenharmony_ci
10357db96d56Sopenharmony_ci   Returns a list of the supported start methods, the first of which
10367db96d56Sopenharmony_ci   is the default.  The possible start methods are ``'fork'``,
10377db96d56Sopenharmony_ci   ``'spawn'`` and ``'forkserver'``.  On Windows only ``'spawn'`` is
10387db96d56Sopenharmony_ci   available.  On Unix ``'fork'`` and ``'spawn'`` are always
10397db96d56Sopenharmony_ci   supported, with ``'fork'`` being the default.
10407db96d56Sopenharmony_ci
10417db96d56Sopenharmony_ci   .. versionadded:: 3.4
10427db96d56Sopenharmony_ci
10437db96d56Sopenharmony_ci.. function:: get_context(method=None)
10447db96d56Sopenharmony_ci
10457db96d56Sopenharmony_ci   Return a context object which has the same attributes as the
10467db96d56Sopenharmony_ci   :mod:`multiprocessing` module.
10477db96d56Sopenharmony_ci
10487db96d56Sopenharmony_ci   If *method* is ``None`` then the default context is returned.
10497db96d56Sopenharmony_ci   Otherwise *method* should be ``'fork'``, ``'spawn'``,
10507db96d56Sopenharmony_ci   ``'forkserver'``.  :exc:`ValueError` is raised if the specified
10517db96d56Sopenharmony_ci   start method is not available.
10527db96d56Sopenharmony_ci
10537db96d56Sopenharmony_ci   .. versionadded:: 3.4
10547db96d56Sopenharmony_ci
10557db96d56Sopenharmony_ci.. function:: get_start_method(allow_none=False)
10567db96d56Sopenharmony_ci
10577db96d56Sopenharmony_ci   Return the name of start method used for starting processes.
10587db96d56Sopenharmony_ci
10597db96d56Sopenharmony_ci   If the start method has not been fixed and *allow_none* is false,
10607db96d56Sopenharmony_ci   then the start method is fixed to the default and the name is
10617db96d56Sopenharmony_ci   returned.  If the start method has not been fixed and *allow_none*
10627db96d56Sopenharmony_ci   is true then ``None`` is returned.
10637db96d56Sopenharmony_ci
10647db96d56Sopenharmony_ci   The return value can be ``'fork'``, ``'spawn'``, ``'forkserver'``
10657db96d56Sopenharmony_ci   or ``None``.  ``'fork'`` is the default on Unix, while ``'spawn'`` is
10667db96d56Sopenharmony_ci   the default on Windows and macOS.
10677db96d56Sopenharmony_ci
10687db96d56Sopenharmony_ci.. versionchanged:: 3.8
10697db96d56Sopenharmony_ci
10707db96d56Sopenharmony_ci   On macOS, the *spawn* start method is now the default.  The *fork* start
10717db96d56Sopenharmony_ci   method should be considered unsafe as it can lead to crashes of the
10727db96d56Sopenharmony_ci   subprocess. See :issue:`33725`.
10737db96d56Sopenharmony_ci
10747db96d56Sopenharmony_ci   .. versionadded:: 3.4
10757db96d56Sopenharmony_ci
10767db96d56Sopenharmony_ci.. function:: set_executable(executable)
10777db96d56Sopenharmony_ci
10787db96d56Sopenharmony_ci   Set the path of the Python interpreter to use when starting a child process.
10797db96d56Sopenharmony_ci   (By default :data:`sys.executable` is used).  Embedders will probably need to
10807db96d56Sopenharmony_ci   do some thing like ::
10817db96d56Sopenharmony_ci
10827db96d56Sopenharmony_ci      set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
10837db96d56Sopenharmony_ci
10847db96d56Sopenharmony_ci   before they can create child processes.
10857db96d56Sopenharmony_ci
10867db96d56Sopenharmony_ci   .. versionchanged:: 3.4
10877db96d56Sopenharmony_ci      Now supported on Unix when the ``'spawn'`` start method is used.
10887db96d56Sopenharmony_ci
10897db96d56Sopenharmony_ci   .. versionchanged:: 3.11
10907db96d56Sopenharmony_ci      Accepts a :term:`path-like object`.
10917db96d56Sopenharmony_ci
10927db96d56Sopenharmony_ci.. function:: set_start_method(method, force=False)
10937db96d56Sopenharmony_ci
10947db96d56Sopenharmony_ci   Set the method which should be used to start child processes.
10957db96d56Sopenharmony_ci   The *method* argument can be ``'fork'``, ``'spawn'`` or ``'forkserver'``.
10967db96d56Sopenharmony_ci   Raises :exc:`RuntimeError` if the start method has already been set and *force*
10977db96d56Sopenharmony_ci   is not ``True``.  If *method* is ``None`` and *force* is ``True`` then the start
10987db96d56Sopenharmony_ci   method is set to ``None``.  If *method* is ``None`` and *force* is ``False``
10997db96d56Sopenharmony_ci   then the context is set to the default context.
11007db96d56Sopenharmony_ci
11017db96d56Sopenharmony_ci   Note that this should be called at most once, and it should be
11027db96d56Sopenharmony_ci   protected inside the ``if __name__ == '__main__'`` clause of the
11037db96d56Sopenharmony_ci   main module.
11047db96d56Sopenharmony_ci
11057db96d56Sopenharmony_ci   .. versionadded:: 3.4
11067db96d56Sopenharmony_ci
11077db96d56Sopenharmony_ci.. note::
11087db96d56Sopenharmony_ci
11097db96d56Sopenharmony_ci   :mod:`multiprocessing` contains no analogues of
11107db96d56Sopenharmony_ci   :func:`threading.active_count`, :func:`threading.enumerate`,
11117db96d56Sopenharmony_ci   :func:`threading.settrace`, :func:`threading.setprofile`,
11127db96d56Sopenharmony_ci   :class:`threading.Timer`, or :class:`threading.local`.
11137db96d56Sopenharmony_ci
11147db96d56Sopenharmony_ci
11157db96d56Sopenharmony_ciConnection Objects
11167db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~
11177db96d56Sopenharmony_ci
11187db96d56Sopenharmony_ci.. currentmodule:: multiprocessing.connection
11197db96d56Sopenharmony_ci
11207db96d56Sopenharmony_ciConnection objects allow the sending and receiving of picklable objects or
11217db96d56Sopenharmony_cistrings.  They can be thought of as message oriented connected sockets.
11227db96d56Sopenharmony_ci
11237db96d56Sopenharmony_ciConnection objects are usually created using
11247db96d56Sopenharmony_ci:func:`Pipe <multiprocessing.Pipe>` -- see also
11257db96d56Sopenharmony_ci:ref:`multiprocessing-listeners-clients`.
11267db96d56Sopenharmony_ci
11277db96d56Sopenharmony_ci.. class:: Connection
11287db96d56Sopenharmony_ci
11297db96d56Sopenharmony_ci   .. method:: send(obj)
11307db96d56Sopenharmony_ci
11317db96d56Sopenharmony_ci      Send an object to the other end of the connection which should be read
11327db96d56Sopenharmony_ci      using :meth:`recv`.
11337db96d56Sopenharmony_ci
11347db96d56Sopenharmony_ci      The object must be picklable.  Very large pickles (approximately 32 MiB+,
11357db96d56Sopenharmony_ci      though it depends on the OS) may raise a :exc:`ValueError` exception.
11367db96d56Sopenharmony_ci
11377db96d56Sopenharmony_ci   .. method:: recv()
11387db96d56Sopenharmony_ci
11397db96d56Sopenharmony_ci      Return an object sent from the other end of the connection using
11407db96d56Sopenharmony_ci      :meth:`send`.  Blocks until there is something to receive.  Raises
11417db96d56Sopenharmony_ci      :exc:`EOFError` if there is nothing left to receive
11427db96d56Sopenharmony_ci      and the other end was closed.
11437db96d56Sopenharmony_ci
11447db96d56Sopenharmony_ci   .. method:: fileno()
11457db96d56Sopenharmony_ci
11467db96d56Sopenharmony_ci      Return the file descriptor or handle used by the connection.
11477db96d56Sopenharmony_ci
11487db96d56Sopenharmony_ci   .. method:: close()
11497db96d56Sopenharmony_ci
11507db96d56Sopenharmony_ci      Close the connection.
11517db96d56Sopenharmony_ci
11527db96d56Sopenharmony_ci      This is called automatically when the connection is garbage collected.
11537db96d56Sopenharmony_ci
11547db96d56Sopenharmony_ci   .. method:: poll([timeout])
11557db96d56Sopenharmony_ci
11567db96d56Sopenharmony_ci      Return whether there is any data available to be read.
11577db96d56Sopenharmony_ci
11587db96d56Sopenharmony_ci      If *timeout* is not specified then it will return immediately.  If
11597db96d56Sopenharmony_ci      *timeout* is a number then this specifies the maximum time in seconds to
11607db96d56Sopenharmony_ci      block.  If *timeout* is ``None`` then an infinite timeout is used.
11617db96d56Sopenharmony_ci
11627db96d56Sopenharmony_ci      Note that multiple connection objects may be polled at once by
11637db96d56Sopenharmony_ci      using :func:`multiprocessing.connection.wait`.
11647db96d56Sopenharmony_ci
11657db96d56Sopenharmony_ci   .. method:: send_bytes(buffer[, offset[, size]])
11667db96d56Sopenharmony_ci
11677db96d56Sopenharmony_ci      Send byte data from a :term:`bytes-like object` as a complete message.
11687db96d56Sopenharmony_ci
11697db96d56Sopenharmony_ci      If *offset* is given then data is read from that position in *buffer*.  If
11707db96d56Sopenharmony_ci      *size* is given then that many bytes will be read from buffer.  Very large
11717db96d56Sopenharmony_ci      buffers (approximately 32 MiB+, though it depends on the OS) may raise a
11727db96d56Sopenharmony_ci      :exc:`ValueError` exception
11737db96d56Sopenharmony_ci
11747db96d56Sopenharmony_ci   .. method:: recv_bytes([maxlength])
11757db96d56Sopenharmony_ci
11767db96d56Sopenharmony_ci      Return a complete message of byte data sent from the other end of the
11777db96d56Sopenharmony_ci      connection as a string.  Blocks until there is something to receive.
11787db96d56Sopenharmony_ci      Raises :exc:`EOFError` if there is nothing left
11797db96d56Sopenharmony_ci      to receive and the other end has closed.
11807db96d56Sopenharmony_ci
11817db96d56Sopenharmony_ci      If *maxlength* is specified and the message is longer than *maxlength*
11827db96d56Sopenharmony_ci      then :exc:`OSError` is raised and the connection will no longer be
11837db96d56Sopenharmony_ci      readable.
11847db96d56Sopenharmony_ci
11857db96d56Sopenharmony_ci      .. versionchanged:: 3.3
11867db96d56Sopenharmony_ci         This function used to raise :exc:`IOError`, which is now an
11877db96d56Sopenharmony_ci         alias of :exc:`OSError`.
11887db96d56Sopenharmony_ci
11897db96d56Sopenharmony_ci
11907db96d56Sopenharmony_ci   .. method:: recv_bytes_into(buffer[, offset])
11917db96d56Sopenharmony_ci
11927db96d56Sopenharmony_ci      Read into *buffer* a complete message of byte data sent from the other end
11937db96d56Sopenharmony_ci      of the connection and return the number of bytes in the message.  Blocks
11947db96d56Sopenharmony_ci      until there is something to receive.  Raises
11957db96d56Sopenharmony_ci      :exc:`EOFError` if there is nothing left to receive and the other end was
11967db96d56Sopenharmony_ci      closed.
11977db96d56Sopenharmony_ci
11987db96d56Sopenharmony_ci      *buffer* must be a writable :term:`bytes-like object`.  If
11997db96d56Sopenharmony_ci      *offset* is given then the message will be written into the buffer from
12007db96d56Sopenharmony_ci      that position.  Offset must be a non-negative integer less than the
12017db96d56Sopenharmony_ci      length of *buffer* (in bytes).
12027db96d56Sopenharmony_ci
12037db96d56Sopenharmony_ci      If the buffer is too short then a :exc:`BufferTooShort` exception is
12047db96d56Sopenharmony_ci      raised and the complete message is available as ``e.args[0]`` where ``e``
12057db96d56Sopenharmony_ci      is the exception instance.
12067db96d56Sopenharmony_ci
12077db96d56Sopenharmony_ci   .. versionchanged:: 3.3
12087db96d56Sopenharmony_ci      Connection objects themselves can now be transferred between processes
12097db96d56Sopenharmony_ci      using :meth:`Connection.send` and :meth:`Connection.recv`.
12107db96d56Sopenharmony_ci
12117db96d56Sopenharmony_ci   .. versionadded:: 3.3
12127db96d56Sopenharmony_ci      Connection objects now support the context management protocol -- see
12137db96d56Sopenharmony_ci      :ref:`typecontextmanager`.  :meth:`~contextmanager.__enter__` returns the
12147db96d56Sopenharmony_ci      connection object, and :meth:`~contextmanager.__exit__` calls :meth:`close`.
12157db96d56Sopenharmony_ci
12167db96d56Sopenharmony_ciFor example:
12177db96d56Sopenharmony_ci
12187db96d56Sopenharmony_ci.. doctest::
12197db96d56Sopenharmony_ci
12207db96d56Sopenharmony_ci    >>> from multiprocessing import Pipe
12217db96d56Sopenharmony_ci    >>> a, b = Pipe()
12227db96d56Sopenharmony_ci    >>> a.send([1, 'hello', None])
12237db96d56Sopenharmony_ci    >>> b.recv()
12247db96d56Sopenharmony_ci    [1, 'hello', None]
12257db96d56Sopenharmony_ci    >>> b.send_bytes(b'thank you')
12267db96d56Sopenharmony_ci    >>> a.recv_bytes()
12277db96d56Sopenharmony_ci    b'thank you'
12287db96d56Sopenharmony_ci    >>> import array
12297db96d56Sopenharmony_ci    >>> arr1 = array.array('i', range(5))
12307db96d56Sopenharmony_ci    >>> arr2 = array.array('i', [0] * 10)
12317db96d56Sopenharmony_ci    >>> a.send_bytes(arr1)
12327db96d56Sopenharmony_ci    >>> count = b.recv_bytes_into(arr2)
12337db96d56Sopenharmony_ci    >>> assert count == len(arr1) * arr1.itemsize
12347db96d56Sopenharmony_ci    >>> arr2
12357db96d56Sopenharmony_ci    array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
12367db96d56Sopenharmony_ci
12377db96d56Sopenharmony_ci.. _multiprocessing-recv-pickle-security:
12387db96d56Sopenharmony_ci
12397db96d56Sopenharmony_ci.. warning::
12407db96d56Sopenharmony_ci
12417db96d56Sopenharmony_ci    The :meth:`Connection.recv` method automatically unpickles the data it
12427db96d56Sopenharmony_ci    receives, which can be a security risk unless you can trust the process
12437db96d56Sopenharmony_ci    which sent the message.
12447db96d56Sopenharmony_ci
12457db96d56Sopenharmony_ci    Therefore, unless the connection object was produced using :func:`Pipe` you
12467db96d56Sopenharmony_ci    should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
12477db96d56Sopenharmony_ci    methods after performing some sort of authentication.  See
12487db96d56Sopenharmony_ci    :ref:`multiprocessing-auth-keys`.
12497db96d56Sopenharmony_ci
12507db96d56Sopenharmony_ci.. warning::
12517db96d56Sopenharmony_ci
12527db96d56Sopenharmony_ci    If a process is killed while it is trying to read or write to a pipe then
12537db96d56Sopenharmony_ci    the data in the pipe is likely to become corrupted, because it may become
12547db96d56Sopenharmony_ci    impossible to be sure where the message boundaries lie.
12557db96d56Sopenharmony_ci
12567db96d56Sopenharmony_ci
12577db96d56Sopenharmony_ciSynchronization primitives
12587db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~
12597db96d56Sopenharmony_ci
12607db96d56Sopenharmony_ci.. currentmodule:: multiprocessing
12617db96d56Sopenharmony_ci
12627db96d56Sopenharmony_ciGenerally synchronization primitives are not as necessary in a multiprocess
12637db96d56Sopenharmony_ciprogram as they are in a multithreaded program.  See the documentation for
12647db96d56Sopenharmony_ci:mod:`threading` module.
12657db96d56Sopenharmony_ci
12667db96d56Sopenharmony_ciNote that one can also create synchronization primitives by using a manager
12677db96d56Sopenharmony_ciobject -- see :ref:`multiprocessing-managers`.
12687db96d56Sopenharmony_ci
12697db96d56Sopenharmony_ci.. class:: Barrier(parties[, action[, timeout]])
12707db96d56Sopenharmony_ci
12717db96d56Sopenharmony_ci   A barrier object: a clone of :class:`threading.Barrier`.
12727db96d56Sopenharmony_ci
12737db96d56Sopenharmony_ci   .. versionadded:: 3.3
12747db96d56Sopenharmony_ci
12757db96d56Sopenharmony_ci.. class:: BoundedSemaphore([value])
12767db96d56Sopenharmony_ci
12777db96d56Sopenharmony_ci   A bounded semaphore object: a close analog of
12787db96d56Sopenharmony_ci   :class:`threading.BoundedSemaphore`.
12797db96d56Sopenharmony_ci
12807db96d56Sopenharmony_ci   A solitary difference from its close analog exists: its ``acquire`` method's
12817db96d56Sopenharmony_ci   first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
12827db96d56Sopenharmony_ci
12837db96d56Sopenharmony_ci   .. note::
12847db96d56Sopenharmony_ci      On macOS, this is indistinguishable from :class:`Semaphore` because
12857db96d56Sopenharmony_ci      ``sem_getvalue()`` is not implemented on that platform.
12867db96d56Sopenharmony_ci
12877db96d56Sopenharmony_ci.. class:: Condition([lock])
12887db96d56Sopenharmony_ci
12897db96d56Sopenharmony_ci   A condition variable: an alias for :class:`threading.Condition`.
12907db96d56Sopenharmony_ci
12917db96d56Sopenharmony_ci   If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
12927db96d56Sopenharmony_ci   object from :mod:`multiprocessing`.
12937db96d56Sopenharmony_ci
12947db96d56Sopenharmony_ci   .. versionchanged:: 3.3
12957db96d56Sopenharmony_ci      The :meth:`~threading.Condition.wait_for` method was added.
12967db96d56Sopenharmony_ci
12977db96d56Sopenharmony_ci.. class:: Event()
12987db96d56Sopenharmony_ci
12997db96d56Sopenharmony_ci   A clone of :class:`threading.Event`.
13007db96d56Sopenharmony_ci
13017db96d56Sopenharmony_ci
13027db96d56Sopenharmony_ci.. class:: Lock()
13037db96d56Sopenharmony_ci
13047db96d56Sopenharmony_ci   A non-recursive lock object: a close analog of :class:`threading.Lock`.
13057db96d56Sopenharmony_ci   Once a process or thread has acquired a lock, subsequent attempts to
13067db96d56Sopenharmony_ci   acquire it from any process or thread will block until it is released;
13077db96d56Sopenharmony_ci   any process or thread may release it.  The concepts and behaviors of
13087db96d56Sopenharmony_ci   :class:`threading.Lock` as it applies to threads are replicated here in
13097db96d56Sopenharmony_ci   :class:`multiprocessing.Lock` as it applies to either processes or threads,
13107db96d56Sopenharmony_ci   except as noted.
13117db96d56Sopenharmony_ci
13127db96d56Sopenharmony_ci   Note that :class:`Lock` is actually a factory function which returns an
13137db96d56Sopenharmony_ci   instance of ``multiprocessing.synchronize.Lock`` initialized with a
13147db96d56Sopenharmony_ci   default context.
13157db96d56Sopenharmony_ci
13167db96d56Sopenharmony_ci   :class:`Lock` supports the :term:`context manager` protocol and thus may be
13177db96d56Sopenharmony_ci   used in :keyword:`with` statements.
13187db96d56Sopenharmony_ci
13197db96d56Sopenharmony_ci   .. method:: acquire(block=True, timeout=None)
13207db96d56Sopenharmony_ci
13217db96d56Sopenharmony_ci      Acquire a lock, blocking or non-blocking.
13227db96d56Sopenharmony_ci
13237db96d56Sopenharmony_ci      With the *block* argument set to ``True`` (the default), the method call
13247db96d56Sopenharmony_ci      will block until the lock is in an unlocked state, then set it to locked
13257db96d56Sopenharmony_ci      and return ``True``.  Note that the name of this first argument differs
13267db96d56Sopenharmony_ci      from that in :meth:`threading.Lock.acquire`.
13277db96d56Sopenharmony_ci
13287db96d56Sopenharmony_ci      With the *block* argument set to ``False``, the method call does not
13297db96d56Sopenharmony_ci      block.  If the lock is currently in a locked state, return ``False``;
13307db96d56Sopenharmony_ci      otherwise set the lock to a locked state and return ``True``.
13317db96d56Sopenharmony_ci
13327db96d56Sopenharmony_ci      When invoked with a positive, floating-point value for *timeout*, block
13337db96d56Sopenharmony_ci      for at most the number of seconds specified by *timeout* as long as
13347db96d56Sopenharmony_ci      the lock can not be acquired.  Invocations with a negative value for
13357db96d56Sopenharmony_ci      *timeout* are equivalent to a *timeout* of zero.  Invocations with a
13367db96d56Sopenharmony_ci      *timeout* value of ``None`` (the default) set the timeout period to
13377db96d56Sopenharmony_ci      infinite.  Note that the treatment of negative or ``None`` values for
13387db96d56Sopenharmony_ci      *timeout* differs from the implemented behavior in
13397db96d56Sopenharmony_ci      :meth:`threading.Lock.acquire`.  The *timeout* argument has no practical
13407db96d56Sopenharmony_ci      implications if the *block* argument is set to ``False`` and is thus
13417db96d56Sopenharmony_ci      ignored.  Returns ``True`` if the lock has been acquired or ``False`` if
13427db96d56Sopenharmony_ci      the timeout period has elapsed.
13437db96d56Sopenharmony_ci
13447db96d56Sopenharmony_ci
13457db96d56Sopenharmony_ci   .. method:: release()
13467db96d56Sopenharmony_ci
13477db96d56Sopenharmony_ci      Release a lock.  This can be called from any process or thread, not only
13487db96d56Sopenharmony_ci      the process or thread which originally acquired the lock.
13497db96d56Sopenharmony_ci
13507db96d56Sopenharmony_ci      Behavior is the same as in :meth:`threading.Lock.release` except that
13517db96d56Sopenharmony_ci      when invoked on an unlocked lock, a :exc:`ValueError` is raised.
13527db96d56Sopenharmony_ci
13537db96d56Sopenharmony_ci
13547db96d56Sopenharmony_ci.. class:: RLock()
13557db96d56Sopenharmony_ci
13567db96d56Sopenharmony_ci   A recursive lock object: a close analog of :class:`threading.RLock`.  A
13577db96d56Sopenharmony_ci   recursive lock must be released by the process or thread that acquired it.
13587db96d56Sopenharmony_ci   Once a process or thread has acquired a recursive lock, the same process
13597db96d56Sopenharmony_ci   or thread may acquire it again without blocking; that process or thread
13607db96d56Sopenharmony_ci   must release it once for each time it has been acquired.
13617db96d56Sopenharmony_ci
13627db96d56Sopenharmony_ci   Note that :class:`RLock` is actually a factory function which returns an
13637db96d56Sopenharmony_ci   instance of ``multiprocessing.synchronize.RLock`` initialized with a
13647db96d56Sopenharmony_ci   default context.
13657db96d56Sopenharmony_ci
13667db96d56Sopenharmony_ci   :class:`RLock` supports the :term:`context manager` protocol and thus may be
13677db96d56Sopenharmony_ci   used in :keyword:`with` statements.
13687db96d56Sopenharmony_ci
13697db96d56Sopenharmony_ci
13707db96d56Sopenharmony_ci   .. method:: acquire(block=True, timeout=None)
13717db96d56Sopenharmony_ci
13727db96d56Sopenharmony_ci      Acquire a lock, blocking or non-blocking.
13737db96d56Sopenharmony_ci
13747db96d56Sopenharmony_ci      When invoked with the *block* argument set to ``True``, block until the
13757db96d56Sopenharmony_ci      lock is in an unlocked state (not owned by any process or thread) unless
13767db96d56Sopenharmony_ci      the lock is already owned by the current process or thread.  The current
13777db96d56Sopenharmony_ci      process or thread then takes ownership of the lock (if it does not
13787db96d56Sopenharmony_ci      already have ownership) and the recursion level inside the lock increments
13797db96d56Sopenharmony_ci      by one, resulting in a return value of ``True``.  Note that there are
13807db96d56Sopenharmony_ci      several differences in this first argument's behavior compared to the
13817db96d56Sopenharmony_ci      implementation of :meth:`threading.RLock.acquire`, starting with the name
13827db96d56Sopenharmony_ci      of the argument itself.
13837db96d56Sopenharmony_ci
13847db96d56Sopenharmony_ci      When invoked with the *block* argument set to ``False``, do not block.
13857db96d56Sopenharmony_ci      If the lock has already been acquired (and thus is owned) by another
13867db96d56Sopenharmony_ci      process or thread, the current process or thread does not take ownership
13877db96d56Sopenharmony_ci      and the recursion level within the lock is not changed, resulting in
13887db96d56Sopenharmony_ci      a return value of ``False``.  If the lock is in an unlocked state, the
13897db96d56Sopenharmony_ci      current process or thread takes ownership and the recursion level is
13907db96d56Sopenharmony_ci      incremented, resulting in a return value of ``True``.
13917db96d56Sopenharmony_ci
13927db96d56Sopenharmony_ci      Use and behaviors of the *timeout* argument are the same as in
13937db96d56Sopenharmony_ci      :meth:`Lock.acquire`.  Note that some of these behaviors of *timeout*
13947db96d56Sopenharmony_ci      differ from the implemented behaviors in :meth:`threading.RLock.acquire`.
13957db96d56Sopenharmony_ci
13967db96d56Sopenharmony_ci
13977db96d56Sopenharmony_ci   .. method:: release()
13987db96d56Sopenharmony_ci
13997db96d56Sopenharmony_ci      Release a lock, decrementing the recursion level.  If after the
14007db96d56Sopenharmony_ci      decrement the recursion level is zero, reset the lock to unlocked (not
14017db96d56Sopenharmony_ci      owned by any process or thread) and if any other processes or threads
14027db96d56Sopenharmony_ci      are blocked waiting for the lock to become unlocked, allow exactly one
14037db96d56Sopenharmony_ci      of them to proceed.  If after the decrement the recursion level is still
14047db96d56Sopenharmony_ci      nonzero, the lock remains locked and owned by the calling process or
14057db96d56Sopenharmony_ci      thread.
14067db96d56Sopenharmony_ci
14077db96d56Sopenharmony_ci      Only call this method when the calling process or thread owns the lock.
14087db96d56Sopenharmony_ci      An :exc:`AssertionError` is raised if this method is called by a process
14097db96d56Sopenharmony_ci      or thread other than the owner or if the lock is in an unlocked (unowned)
14107db96d56Sopenharmony_ci      state.  Note that the type of exception raised in this situation
14117db96d56Sopenharmony_ci      differs from the implemented behavior in :meth:`threading.RLock.release`.
14127db96d56Sopenharmony_ci
14137db96d56Sopenharmony_ci
14147db96d56Sopenharmony_ci.. class:: Semaphore([value])
14157db96d56Sopenharmony_ci
14167db96d56Sopenharmony_ci   A semaphore object: a close analog of :class:`threading.Semaphore`.
14177db96d56Sopenharmony_ci
14187db96d56Sopenharmony_ci   A solitary difference from its close analog exists: its ``acquire`` method's
14197db96d56Sopenharmony_ci   first argument is named *block*, as is consistent with :meth:`Lock.acquire`.
14207db96d56Sopenharmony_ci
14217db96d56Sopenharmony_ci.. note::
14227db96d56Sopenharmony_ci
14237db96d56Sopenharmony_ci   On macOS, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
14247db96d56Sopenharmony_ci   a timeout will emulate that function's behavior using a sleeping loop.
14257db96d56Sopenharmony_ci
14267db96d56Sopenharmony_ci.. note::
14277db96d56Sopenharmony_ci
14287db96d56Sopenharmony_ci   If the SIGINT signal generated by :kbd:`Ctrl-C` arrives while the main thread is
14297db96d56Sopenharmony_ci   blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
14307db96d56Sopenharmony_ci   :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
14317db96d56Sopenharmony_ci   or :meth:`Condition.wait` then the call will be immediately interrupted and
14327db96d56Sopenharmony_ci   :exc:`KeyboardInterrupt` will be raised.
14337db96d56Sopenharmony_ci
14347db96d56Sopenharmony_ci   This differs from the behaviour of :mod:`threading` where SIGINT will be
14357db96d56Sopenharmony_ci   ignored while the equivalent blocking calls are in progress.
14367db96d56Sopenharmony_ci
14377db96d56Sopenharmony_ci.. note::
14387db96d56Sopenharmony_ci
14397db96d56Sopenharmony_ci   Some of this package's functionality requires a functioning shared semaphore
14407db96d56Sopenharmony_ci   implementation on the host operating system. Without one, the
14417db96d56Sopenharmony_ci   :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
14427db96d56Sopenharmony_ci   import it will result in an :exc:`ImportError`. See
14437db96d56Sopenharmony_ci   :issue:`3770` for additional information.
14447db96d56Sopenharmony_ci
14457db96d56Sopenharmony_ci
14467db96d56Sopenharmony_ciShared :mod:`ctypes` Objects
14477db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14487db96d56Sopenharmony_ci
14497db96d56Sopenharmony_ciIt is possible to create shared objects using shared memory which can be
14507db96d56Sopenharmony_ciinherited by child processes.
14517db96d56Sopenharmony_ci
14527db96d56Sopenharmony_ci.. function:: Value(typecode_or_type, *args, lock=True)
14537db96d56Sopenharmony_ci
14547db96d56Sopenharmony_ci   Return a :mod:`ctypes` object allocated from shared memory.  By default the
14557db96d56Sopenharmony_ci   return value is actually a synchronized wrapper for the object.  The object
14567db96d56Sopenharmony_ci   itself can be accessed via the *value* attribute of a :class:`Value`.
14577db96d56Sopenharmony_ci
14587db96d56Sopenharmony_ci   *typecode_or_type* determines the type of the returned object: it is either a
14597db96d56Sopenharmony_ci   ctypes type or a one character typecode of the kind used by the :mod:`array`
14607db96d56Sopenharmony_ci   module.  *\*args* is passed on to the constructor for the type.
14617db96d56Sopenharmony_ci
14627db96d56Sopenharmony_ci   If *lock* is ``True`` (the default) then a new recursive lock
14637db96d56Sopenharmony_ci   object is created to synchronize access to the value.  If *lock* is
14647db96d56Sopenharmony_ci   a :class:`Lock` or :class:`RLock` object then that will be used to
14657db96d56Sopenharmony_ci   synchronize access to the value.  If *lock* is ``False`` then
14667db96d56Sopenharmony_ci   access to the returned object will not be automatically protected
14677db96d56Sopenharmony_ci   by a lock, so it will not necessarily be "process-safe".
14687db96d56Sopenharmony_ci
14697db96d56Sopenharmony_ci   Operations like ``+=`` which involve a read and write are not
14707db96d56Sopenharmony_ci   atomic.  So if, for instance, you want to atomically increment a
14717db96d56Sopenharmony_ci   shared value it is insufficient to just do ::
14727db96d56Sopenharmony_ci
14737db96d56Sopenharmony_ci       counter.value += 1
14747db96d56Sopenharmony_ci
14757db96d56Sopenharmony_ci   Assuming the associated lock is recursive (which it is by default)
14767db96d56Sopenharmony_ci   you can instead do ::
14777db96d56Sopenharmony_ci
14787db96d56Sopenharmony_ci       with counter.get_lock():
14797db96d56Sopenharmony_ci           counter.value += 1
14807db96d56Sopenharmony_ci
14817db96d56Sopenharmony_ci   Note that *lock* is a keyword-only argument.
14827db96d56Sopenharmony_ci
14837db96d56Sopenharmony_ci.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
14847db96d56Sopenharmony_ci
14857db96d56Sopenharmony_ci   Return a ctypes array allocated from shared memory.  By default the return
14867db96d56Sopenharmony_ci   value is actually a synchronized wrapper for the array.
14877db96d56Sopenharmony_ci
14887db96d56Sopenharmony_ci   *typecode_or_type* determines the type of the elements of the returned array:
14897db96d56Sopenharmony_ci   it is either a ctypes type or a one character typecode of the kind used by
14907db96d56Sopenharmony_ci   the :mod:`array` module.  If *size_or_initializer* is an integer, then it
14917db96d56Sopenharmony_ci   determines the length of the array, and the array will be initially zeroed.
14927db96d56Sopenharmony_ci   Otherwise, *size_or_initializer* is a sequence which is used to initialize
14937db96d56Sopenharmony_ci   the array and whose length determines the length of the array.
14947db96d56Sopenharmony_ci
14957db96d56Sopenharmony_ci   If *lock* is ``True`` (the default) then a new lock object is created to
14967db96d56Sopenharmony_ci   synchronize access to the value.  If *lock* is a :class:`Lock` or
14977db96d56Sopenharmony_ci   :class:`RLock` object then that will be used to synchronize access to the
14987db96d56Sopenharmony_ci   value.  If *lock* is ``False`` then access to the returned object will not be
14997db96d56Sopenharmony_ci   automatically protected by a lock, so it will not necessarily be
15007db96d56Sopenharmony_ci   "process-safe".
15017db96d56Sopenharmony_ci
15027db96d56Sopenharmony_ci   Note that *lock* is a keyword only argument.
15037db96d56Sopenharmony_ci
15047db96d56Sopenharmony_ci   Note that an array of :data:`ctypes.c_char` has *value* and *raw*
15057db96d56Sopenharmony_ci   attributes which allow one to use it to store and retrieve strings.
15067db96d56Sopenharmony_ci
15077db96d56Sopenharmony_ci
15087db96d56Sopenharmony_ciThe :mod:`multiprocessing.sharedctypes` module
15097db96d56Sopenharmony_ci>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
15107db96d56Sopenharmony_ci
15117db96d56Sopenharmony_ci.. module:: multiprocessing.sharedctypes
15127db96d56Sopenharmony_ci   :synopsis: Allocate ctypes objects from shared memory.
15137db96d56Sopenharmony_ci
15147db96d56Sopenharmony_ciThe :mod:`multiprocessing.sharedctypes` module provides functions for allocating
15157db96d56Sopenharmony_ci:mod:`ctypes` objects from shared memory which can be inherited by child
15167db96d56Sopenharmony_ciprocesses.
15177db96d56Sopenharmony_ci
15187db96d56Sopenharmony_ci.. note::
15197db96d56Sopenharmony_ci
15207db96d56Sopenharmony_ci   Although it is possible to store a pointer in shared memory remember that
15217db96d56Sopenharmony_ci   this will refer to a location in the address space of a specific process.
15227db96d56Sopenharmony_ci   However, the pointer is quite likely to be invalid in the context of a second
15237db96d56Sopenharmony_ci   process and trying to dereference the pointer from the second process may
15247db96d56Sopenharmony_ci   cause a crash.
15257db96d56Sopenharmony_ci
15267db96d56Sopenharmony_ci.. function:: RawArray(typecode_or_type, size_or_initializer)
15277db96d56Sopenharmony_ci
15287db96d56Sopenharmony_ci   Return a ctypes array allocated from shared memory.
15297db96d56Sopenharmony_ci
15307db96d56Sopenharmony_ci   *typecode_or_type* determines the type of the elements of the returned array:
15317db96d56Sopenharmony_ci   it is either a ctypes type or a one character typecode of the kind used by
15327db96d56Sopenharmony_ci   the :mod:`array` module.  If *size_or_initializer* is an integer then it
15337db96d56Sopenharmony_ci   determines the length of the array, and the array will be initially zeroed.
15347db96d56Sopenharmony_ci   Otherwise *size_or_initializer* is a sequence which is used to initialize the
15357db96d56Sopenharmony_ci   array and whose length determines the length of the array.
15367db96d56Sopenharmony_ci
15377db96d56Sopenharmony_ci   Note that setting and getting an element is potentially non-atomic -- use
15387db96d56Sopenharmony_ci   :func:`Array` instead to make sure that access is automatically synchronized
15397db96d56Sopenharmony_ci   using a lock.
15407db96d56Sopenharmony_ci
15417db96d56Sopenharmony_ci.. function:: RawValue(typecode_or_type, *args)
15427db96d56Sopenharmony_ci
15437db96d56Sopenharmony_ci   Return a ctypes object allocated from shared memory.
15447db96d56Sopenharmony_ci
15457db96d56Sopenharmony_ci   *typecode_or_type* determines the type of the returned object: it is either a
15467db96d56Sopenharmony_ci   ctypes type or a one character typecode of the kind used by the :mod:`array`
15477db96d56Sopenharmony_ci   module.  *\*args* is passed on to the constructor for the type.
15487db96d56Sopenharmony_ci
15497db96d56Sopenharmony_ci   Note that setting and getting the value is potentially non-atomic -- use
15507db96d56Sopenharmony_ci   :func:`Value` instead to make sure that access is automatically synchronized
15517db96d56Sopenharmony_ci   using a lock.
15527db96d56Sopenharmony_ci
15537db96d56Sopenharmony_ci   Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
15547db96d56Sopenharmony_ci   attributes which allow one to use it to store and retrieve strings -- see
15557db96d56Sopenharmony_ci   documentation for :mod:`ctypes`.
15567db96d56Sopenharmony_ci
15577db96d56Sopenharmony_ci.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
15587db96d56Sopenharmony_ci
15597db96d56Sopenharmony_ci   The same as :func:`RawArray` except that depending on the value of *lock* a
15607db96d56Sopenharmony_ci   process-safe synchronization wrapper may be returned instead of a raw ctypes
15617db96d56Sopenharmony_ci   array.
15627db96d56Sopenharmony_ci
15637db96d56Sopenharmony_ci   If *lock* is ``True`` (the default) then a new lock object is created to
15647db96d56Sopenharmony_ci   synchronize access to the value.  If *lock* is a
15657db96d56Sopenharmony_ci   :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
15667db96d56Sopenharmony_ci   then that will be used to synchronize access to the
15677db96d56Sopenharmony_ci   value.  If *lock* is ``False`` then access to the returned object will not be
15687db96d56Sopenharmony_ci   automatically protected by a lock, so it will not necessarily be
15697db96d56Sopenharmony_ci   "process-safe".
15707db96d56Sopenharmony_ci
15717db96d56Sopenharmony_ci   Note that *lock* is a keyword-only argument.
15727db96d56Sopenharmony_ci
15737db96d56Sopenharmony_ci.. function:: Value(typecode_or_type, *args, lock=True)
15747db96d56Sopenharmony_ci
15757db96d56Sopenharmony_ci   The same as :func:`RawValue` except that depending on the value of *lock* a
15767db96d56Sopenharmony_ci   process-safe synchronization wrapper may be returned instead of a raw ctypes
15777db96d56Sopenharmony_ci   object.
15787db96d56Sopenharmony_ci
15797db96d56Sopenharmony_ci   If *lock* is ``True`` (the default) then a new lock object is created to
15807db96d56Sopenharmony_ci   synchronize access to the value.  If *lock* is a :class:`~multiprocessing.Lock` or
15817db96d56Sopenharmony_ci   :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
15827db96d56Sopenharmony_ci   value.  If *lock* is ``False`` then access to the returned object will not be
15837db96d56Sopenharmony_ci   automatically protected by a lock, so it will not necessarily be
15847db96d56Sopenharmony_ci   "process-safe".
15857db96d56Sopenharmony_ci
15867db96d56Sopenharmony_ci   Note that *lock* is a keyword-only argument.
15877db96d56Sopenharmony_ci
15887db96d56Sopenharmony_ci.. function:: copy(obj)
15897db96d56Sopenharmony_ci
15907db96d56Sopenharmony_ci   Return a ctypes object allocated from shared memory which is a copy of the
15917db96d56Sopenharmony_ci   ctypes object *obj*.
15927db96d56Sopenharmony_ci
15937db96d56Sopenharmony_ci.. function:: synchronized(obj[, lock])
15947db96d56Sopenharmony_ci
15957db96d56Sopenharmony_ci   Return a process-safe wrapper object for a ctypes object which uses *lock* to
15967db96d56Sopenharmony_ci   synchronize access.  If *lock* is ``None`` (the default) then a
15977db96d56Sopenharmony_ci   :class:`multiprocessing.RLock` object is created automatically.
15987db96d56Sopenharmony_ci
15997db96d56Sopenharmony_ci   A synchronized wrapper will have two methods in addition to those of the
16007db96d56Sopenharmony_ci   object it wraps: :meth:`get_obj` returns the wrapped object and
16017db96d56Sopenharmony_ci   :meth:`get_lock` returns the lock object used for synchronization.
16027db96d56Sopenharmony_ci
16037db96d56Sopenharmony_ci   Note that accessing the ctypes object through the wrapper can be a lot slower
16047db96d56Sopenharmony_ci   than accessing the raw ctypes object.
16057db96d56Sopenharmony_ci
16067db96d56Sopenharmony_ci   .. versionchanged:: 3.5
16077db96d56Sopenharmony_ci      Synchronized objects support the :term:`context manager` protocol.
16087db96d56Sopenharmony_ci
16097db96d56Sopenharmony_ci
16107db96d56Sopenharmony_ciThe table below compares the syntax for creating shared ctypes objects from
16117db96d56Sopenharmony_cishared memory with the normal ctypes syntax.  (In the table ``MyStruct`` is some
16127db96d56Sopenharmony_cisubclass of :class:`ctypes.Structure`.)
16137db96d56Sopenharmony_ci
16147db96d56Sopenharmony_ci==================== ========================== ===========================
16157db96d56Sopenharmony_cictypes               sharedctypes using type    sharedctypes using typecode
16167db96d56Sopenharmony_ci==================== ========================== ===========================
16177db96d56Sopenharmony_cic_double(2.4)        RawValue(c_double, 2.4)    RawValue('d', 2.4)
16187db96d56Sopenharmony_ciMyStruct(4, 6)       RawValue(MyStruct, 4, 6)
16197db96d56Sopenharmony_ci(c_short * 7)()      RawArray(c_short, 7)       RawArray('h', 7)
16207db96d56Sopenharmony_ci(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
16217db96d56Sopenharmony_ci==================== ========================== ===========================
16227db96d56Sopenharmony_ci
16237db96d56Sopenharmony_ci
16247db96d56Sopenharmony_ciBelow is an example where a number of ctypes objects are modified by a child
16257db96d56Sopenharmony_ciprocess::
16267db96d56Sopenharmony_ci
16277db96d56Sopenharmony_ci   from multiprocessing import Process, Lock
16287db96d56Sopenharmony_ci   from multiprocessing.sharedctypes import Value, Array
16297db96d56Sopenharmony_ci   from ctypes import Structure, c_double
16307db96d56Sopenharmony_ci
16317db96d56Sopenharmony_ci   class Point(Structure):
16327db96d56Sopenharmony_ci       _fields_ = [('x', c_double), ('y', c_double)]
16337db96d56Sopenharmony_ci
16347db96d56Sopenharmony_ci   def modify(n, x, s, A):
16357db96d56Sopenharmony_ci       n.value **= 2
16367db96d56Sopenharmony_ci       x.value **= 2
16377db96d56Sopenharmony_ci       s.value = s.value.upper()
16387db96d56Sopenharmony_ci       for a in A:
16397db96d56Sopenharmony_ci           a.x **= 2
16407db96d56Sopenharmony_ci           a.y **= 2
16417db96d56Sopenharmony_ci
16427db96d56Sopenharmony_ci   if __name__ == '__main__':
16437db96d56Sopenharmony_ci       lock = Lock()
16447db96d56Sopenharmony_ci
16457db96d56Sopenharmony_ci       n = Value('i', 7)
16467db96d56Sopenharmony_ci       x = Value(c_double, 1.0/3.0, lock=False)
16477db96d56Sopenharmony_ci       s = Array('c', b'hello world', lock=lock)
16487db96d56Sopenharmony_ci       A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
16497db96d56Sopenharmony_ci
16507db96d56Sopenharmony_ci       p = Process(target=modify, args=(n, x, s, A))
16517db96d56Sopenharmony_ci       p.start()
16527db96d56Sopenharmony_ci       p.join()
16537db96d56Sopenharmony_ci
16547db96d56Sopenharmony_ci       print(n.value)
16557db96d56Sopenharmony_ci       print(x.value)
16567db96d56Sopenharmony_ci       print(s.value)
16577db96d56Sopenharmony_ci       print([(a.x, a.y) for a in A])
16587db96d56Sopenharmony_ci
16597db96d56Sopenharmony_ci
16607db96d56Sopenharmony_ci.. highlight:: none
16617db96d56Sopenharmony_ci
16627db96d56Sopenharmony_ciThe results printed are ::
16637db96d56Sopenharmony_ci
16647db96d56Sopenharmony_ci    49
16657db96d56Sopenharmony_ci    0.1111111111111111
16667db96d56Sopenharmony_ci    HELLO WORLD
16677db96d56Sopenharmony_ci    [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
16687db96d56Sopenharmony_ci
16697db96d56Sopenharmony_ci.. highlight:: python3
16707db96d56Sopenharmony_ci
16717db96d56Sopenharmony_ci
16727db96d56Sopenharmony_ci.. _multiprocessing-managers:
16737db96d56Sopenharmony_ci
16747db96d56Sopenharmony_ciManagers
16757db96d56Sopenharmony_ci~~~~~~~~
16767db96d56Sopenharmony_ci
16777db96d56Sopenharmony_ciManagers provide a way to create data which can be shared between different
16787db96d56Sopenharmony_ciprocesses, including sharing over a network between processes running on
16797db96d56Sopenharmony_cidifferent machines. A manager object controls a server process which manages
16807db96d56Sopenharmony_ci*shared objects*.  Other processes can access the shared objects by using
16817db96d56Sopenharmony_ciproxies.
16827db96d56Sopenharmony_ci
16837db96d56Sopenharmony_ci.. function:: multiprocessing.Manager()
16847db96d56Sopenharmony_ci   :module:
16857db96d56Sopenharmony_ci
16867db96d56Sopenharmony_ci   Returns a started :class:`~multiprocessing.managers.SyncManager` object which
16877db96d56Sopenharmony_ci   can be used for sharing objects between processes.  The returned manager
16887db96d56Sopenharmony_ci   object corresponds to a spawned child process and has methods which will
16897db96d56Sopenharmony_ci   create shared objects and return corresponding proxies.
16907db96d56Sopenharmony_ci
16917db96d56Sopenharmony_ci.. module:: multiprocessing.managers
16927db96d56Sopenharmony_ci   :synopsis: Share data between process with shared objects.
16937db96d56Sopenharmony_ci
16947db96d56Sopenharmony_ciManager processes will be shutdown as soon as they are garbage collected or
16957db96d56Sopenharmony_citheir parent process exits.  The manager classes are defined in the
16967db96d56Sopenharmony_ci:mod:`multiprocessing.managers` module:
16977db96d56Sopenharmony_ci
16987db96d56Sopenharmony_ci.. class:: BaseManager(address=None, authkey=None, serializer='pickle', ctx=None, *, shutdown_timeout=1.0)
16997db96d56Sopenharmony_ci
17007db96d56Sopenharmony_ci   Create a BaseManager object.
17017db96d56Sopenharmony_ci
17027db96d56Sopenharmony_ci   Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
17037db96d56Sopenharmony_ci   that the manager object refers to a started manager process.
17047db96d56Sopenharmony_ci
17057db96d56Sopenharmony_ci   *address* is the address on which the manager process listens for new
17067db96d56Sopenharmony_ci   connections.  If *address* is ``None`` then an arbitrary one is chosen.
17077db96d56Sopenharmony_ci
17087db96d56Sopenharmony_ci   *authkey* is the authentication key which will be used to check the
17097db96d56Sopenharmony_ci   validity of incoming connections to the server process.  If
17107db96d56Sopenharmony_ci   *authkey* is ``None`` then ``current_process().authkey`` is used.
17117db96d56Sopenharmony_ci   Otherwise *authkey* is used and it must be a byte string.
17127db96d56Sopenharmony_ci
17137db96d56Sopenharmony_ci   *serializer* must be ``'pickle'`` (use :mod:`pickle` serialization) or
17147db96d56Sopenharmony_ci   ``'xmlrpclib'`` (use :mod:`xmlrpc.client` serialization).
17157db96d56Sopenharmony_ci
17167db96d56Sopenharmony_ci   *ctx* is a context object, or ``None`` (use the current context). See the
17177db96d56Sopenharmony_ci   :func:`get_context` function.
17187db96d56Sopenharmony_ci
17197db96d56Sopenharmony_ci   *shutdown_timeout* is a timeout in seconds used to wait until the process
17207db96d56Sopenharmony_ci   used by the manager completes in the :meth:`shutdown` method. If the
17217db96d56Sopenharmony_ci   shutdown times out, the process is terminated. If terminating the process
17227db96d56Sopenharmony_ci   also times out, the process is killed.
17237db96d56Sopenharmony_ci
17247db96d56Sopenharmony_ci   .. versionchanged:: 3.11
17257db96d56Sopenharmony_ci      Added the *shutdown_timeout* parameter.
17267db96d56Sopenharmony_ci
17277db96d56Sopenharmony_ci   .. method:: start([initializer[, initargs]])
17287db96d56Sopenharmony_ci
17297db96d56Sopenharmony_ci      Start a subprocess to start the manager.  If *initializer* is not ``None``
17307db96d56Sopenharmony_ci      then the subprocess will call ``initializer(*initargs)`` when it starts.
17317db96d56Sopenharmony_ci
17327db96d56Sopenharmony_ci   .. method:: get_server()
17337db96d56Sopenharmony_ci
17347db96d56Sopenharmony_ci      Returns a :class:`Server` object which represents the actual server under
17357db96d56Sopenharmony_ci      the control of the Manager. The :class:`Server` object supports the
17367db96d56Sopenharmony_ci      :meth:`serve_forever` method::
17377db96d56Sopenharmony_ci
17387db96d56Sopenharmony_ci      >>> from multiprocessing.managers import BaseManager
17397db96d56Sopenharmony_ci      >>> manager = BaseManager(address=('', 50000), authkey=b'abc')
17407db96d56Sopenharmony_ci      >>> server = manager.get_server()
17417db96d56Sopenharmony_ci      >>> server.serve_forever()
17427db96d56Sopenharmony_ci
17437db96d56Sopenharmony_ci      :class:`Server` additionally has an :attr:`address` attribute.
17447db96d56Sopenharmony_ci
17457db96d56Sopenharmony_ci   .. method:: connect()
17467db96d56Sopenharmony_ci
17477db96d56Sopenharmony_ci      Connect a local manager object to a remote manager process::
17487db96d56Sopenharmony_ci
17497db96d56Sopenharmony_ci      >>> from multiprocessing.managers import BaseManager
17507db96d56Sopenharmony_ci      >>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
17517db96d56Sopenharmony_ci      >>> m.connect()
17527db96d56Sopenharmony_ci
17537db96d56Sopenharmony_ci   .. method:: shutdown()
17547db96d56Sopenharmony_ci
17557db96d56Sopenharmony_ci      Stop the process used by the manager.  This is only available if
17567db96d56Sopenharmony_ci      :meth:`start` has been used to start the server process.
17577db96d56Sopenharmony_ci
17587db96d56Sopenharmony_ci      This can be called multiple times.
17597db96d56Sopenharmony_ci
17607db96d56Sopenharmony_ci   .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
17617db96d56Sopenharmony_ci
17627db96d56Sopenharmony_ci      A classmethod which can be used for registering a type or callable with
17637db96d56Sopenharmony_ci      the manager class.
17647db96d56Sopenharmony_ci
17657db96d56Sopenharmony_ci      *typeid* is a "type identifier" which is used to identify a particular
17667db96d56Sopenharmony_ci      type of shared object.  This must be a string.
17677db96d56Sopenharmony_ci
17687db96d56Sopenharmony_ci      *callable* is a callable used for creating objects for this type
17697db96d56Sopenharmony_ci      identifier.  If a manager instance will be connected to the
17707db96d56Sopenharmony_ci      server using the :meth:`connect` method, or if the
17717db96d56Sopenharmony_ci      *create_method* argument is ``False`` then this can be left as
17727db96d56Sopenharmony_ci      ``None``.
17737db96d56Sopenharmony_ci
17747db96d56Sopenharmony_ci      *proxytype* is a subclass of :class:`BaseProxy` which is used to create
17757db96d56Sopenharmony_ci      proxies for shared objects with this *typeid*.  If ``None`` then a proxy
17767db96d56Sopenharmony_ci      class is created automatically.
17777db96d56Sopenharmony_ci
17787db96d56Sopenharmony_ci      *exposed* is used to specify a sequence of method names which proxies for
17797db96d56Sopenharmony_ci      this typeid should be allowed to access using
17807db96d56Sopenharmony_ci      :meth:`BaseProxy._callmethod`.  (If *exposed* is ``None`` then
17817db96d56Sopenharmony_ci      :attr:`proxytype._exposed_` is used instead if it exists.)  In the case
17827db96d56Sopenharmony_ci      where no exposed list is specified, all "public methods" of the shared
17837db96d56Sopenharmony_ci      object will be accessible.  (Here a "public method" means any attribute
17847db96d56Sopenharmony_ci      which has a :meth:`~object.__call__` method and whose name does not begin
17857db96d56Sopenharmony_ci      with ``'_'``.)
17867db96d56Sopenharmony_ci
17877db96d56Sopenharmony_ci      *method_to_typeid* is a mapping used to specify the return type of those
17887db96d56Sopenharmony_ci      exposed methods which should return a proxy.  It maps method names to
17897db96d56Sopenharmony_ci      typeid strings.  (If *method_to_typeid* is ``None`` then
17907db96d56Sopenharmony_ci      :attr:`proxytype._method_to_typeid_` is used instead if it exists.)  If a
17917db96d56Sopenharmony_ci      method's name is not a key of this mapping or if the mapping is ``None``
17927db96d56Sopenharmony_ci      then the object returned by the method will be copied by value.
17937db96d56Sopenharmony_ci
17947db96d56Sopenharmony_ci      *create_method* determines whether a method should be created with name
17957db96d56Sopenharmony_ci      *typeid* which can be used to tell the server process to create a new
17967db96d56Sopenharmony_ci      shared object and return a proxy for it.  By default it is ``True``.
17977db96d56Sopenharmony_ci
17987db96d56Sopenharmony_ci   :class:`BaseManager` instances also have one read-only property:
17997db96d56Sopenharmony_ci
18007db96d56Sopenharmony_ci   .. attribute:: address
18017db96d56Sopenharmony_ci
18027db96d56Sopenharmony_ci      The address used by the manager.
18037db96d56Sopenharmony_ci
18047db96d56Sopenharmony_ci   .. versionchanged:: 3.3
18057db96d56Sopenharmony_ci      Manager objects support the context management protocol -- see
18067db96d56Sopenharmony_ci      :ref:`typecontextmanager`.  :meth:`~contextmanager.__enter__` starts the
18077db96d56Sopenharmony_ci      server process (if it has not already started) and then returns the
18087db96d56Sopenharmony_ci      manager object.  :meth:`~contextmanager.__exit__` calls :meth:`shutdown`.
18097db96d56Sopenharmony_ci
18107db96d56Sopenharmony_ci      In previous versions :meth:`~contextmanager.__enter__` did not start the
18117db96d56Sopenharmony_ci      manager's server process if it was not already started.
18127db96d56Sopenharmony_ci
18137db96d56Sopenharmony_ci.. class:: SyncManager
18147db96d56Sopenharmony_ci
18157db96d56Sopenharmony_ci   A subclass of :class:`BaseManager` which can be used for the synchronization
18167db96d56Sopenharmony_ci   of processes.  Objects of this type are returned by
18177db96d56Sopenharmony_ci   :func:`multiprocessing.Manager`.
18187db96d56Sopenharmony_ci
18197db96d56Sopenharmony_ci   Its methods create and return :ref:`multiprocessing-proxy_objects` for a
18207db96d56Sopenharmony_ci   number of commonly used data types to be synchronized across processes.
18217db96d56Sopenharmony_ci   This notably includes shared lists and dictionaries.
18227db96d56Sopenharmony_ci
18237db96d56Sopenharmony_ci   .. method:: Barrier(parties[, action[, timeout]])
18247db96d56Sopenharmony_ci
18257db96d56Sopenharmony_ci      Create a shared :class:`threading.Barrier` object and return a
18267db96d56Sopenharmony_ci      proxy for it.
18277db96d56Sopenharmony_ci
18287db96d56Sopenharmony_ci      .. versionadded:: 3.3
18297db96d56Sopenharmony_ci
18307db96d56Sopenharmony_ci   .. method:: BoundedSemaphore([value])
18317db96d56Sopenharmony_ci
18327db96d56Sopenharmony_ci      Create a shared :class:`threading.BoundedSemaphore` object and return a
18337db96d56Sopenharmony_ci      proxy for it.
18347db96d56Sopenharmony_ci
18357db96d56Sopenharmony_ci   .. method:: Condition([lock])
18367db96d56Sopenharmony_ci
18377db96d56Sopenharmony_ci      Create a shared :class:`threading.Condition` object and return a proxy for
18387db96d56Sopenharmony_ci      it.
18397db96d56Sopenharmony_ci
18407db96d56Sopenharmony_ci      If *lock* is supplied then it should be a proxy for a
18417db96d56Sopenharmony_ci      :class:`threading.Lock` or :class:`threading.RLock` object.
18427db96d56Sopenharmony_ci
18437db96d56Sopenharmony_ci      .. versionchanged:: 3.3
18447db96d56Sopenharmony_ci         The :meth:`~threading.Condition.wait_for` method was added.
18457db96d56Sopenharmony_ci
18467db96d56Sopenharmony_ci   .. method:: Event()
18477db96d56Sopenharmony_ci
18487db96d56Sopenharmony_ci      Create a shared :class:`threading.Event` object and return a proxy for it.
18497db96d56Sopenharmony_ci
18507db96d56Sopenharmony_ci   .. method:: Lock()
18517db96d56Sopenharmony_ci
18527db96d56Sopenharmony_ci      Create a shared :class:`threading.Lock` object and return a proxy for it.
18537db96d56Sopenharmony_ci
18547db96d56Sopenharmony_ci   .. method:: Namespace()
18557db96d56Sopenharmony_ci
18567db96d56Sopenharmony_ci      Create a shared :class:`Namespace` object and return a proxy for it.
18577db96d56Sopenharmony_ci
18587db96d56Sopenharmony_ci   .. method:: Queue([maxsize])
18597db96d56Sopenharmony_ci
18607db96d56Sopenharmony_ci      Create a shared :class:`queue.Queue` object and return a proxy for it.
18617db96d56Sopenharmony_ci
18627db96d56Sopenharmony_ci   .. method:: RLock()
18637db96d56Sopenharmony_ci
18647db96d56Sopenharmony_ci      Create a shared :class:`threading.RLock` object and return a proxy for it.
18657db96d56Sopenharmony_ci
18667db96d56Sopenharmony_ci   .. method:: Semaphore([value])
18677db96d56Sopenharmony_ci
18687db96d56Sopenharmony_ci      Create a shared :class:`threading.Semaphore` object and return a proxy for
18697db96d56Sopenharmony_ci      it.
18707db96d56Sopenharmony_ci
18717db96d56Sopenharmony_ci   .. method:: Array(typecode, sequence)
18727db96d56Sopenharmony_ci
18737db96d56Sopenharmony_ci      Create an array and return a proxy for it.
18747db96d56Sopenharmony_ci
18757db96d56Sopenharmony_ci   .. method:: Value(typecode, value)
18767db96d56Sopenharmony_ci
18777db96d56Sopenharmony_ci      Create an object with a writable ``value`` attribute and return a proxy
18787db96d56Sopenharmony_ci      for it.
18797db96d56Sopenharmony_ci
18807db96d56Sopenharmony_ci   .. method:: dict()
18817db96d56Sopenharmony_ci               dict(mapping)
18827db96d56Sopenharmony_ci               dict(sequence)
18837db96d56Sopenharmony_ci
18847db96d56Sopenharmony_ci      Create a shared :class:`dict` object and return a proxy for it.
18857db96d56Sopenharmony_ci
18867db96d56Sopenharmony_ci   .. method:: list()
18877db96d56Sopenharmony_ci               list(sequence)
18887db96d56Sopenharmony_ci
18897db96d56Sopenharmony_ci      Create a shared :class:`list` object and return a proxy for it.
18907db96d56Sopenharmony_ci
18917db96d56Sopenharmony_ci   .. versionchanged:: 3.6
18927db96d56Sopenharmony_ci      Shared objects are capable of being nested.  For example, a shared
18937db96d56Sopenharmony_ci      container object such as a shared list can contain other shared objects
18947db96d56Sopenharmony_ci      which will all be managed and synchronized by the :class:`SyncManager`.
18957db96d56Sopenharmony_ci
18967db96d56Sopenharmony_ci.. class:: Namespace
18977db96d56Sopenharmony_ci
18987db96d56Sopenharmony_ci   A type that can register with :class:`SyncManager`.
18997db96d56Sopenharmony_ci
19007db96d56Sopenharmony_ci   A namespace object has no public methods, but does have writable attributes.
19017db96d56Sopenharmony_ci   Its representation shows the values of its attributes.
19027db96d56Sopenharmony_ci
19037db96d56Sopenharmony_ci   However, when using a proxy for a namespace object, an attribute beginning
19047db96d56Sopenharmony_ci   with ``'_'`` will be an attribute of the proxy and not an attribute of the
19057db96d56Sopenharmony_ci   referent:
19067db96d56Sopenharmony_ci
19077db96d56Sopenharmony_ci   .. doctest::
19087db96d56Sopenharmony_ci
19097db96d56Sopenharmony_ci    >>> manager = multiprocessing.Manager()
19107db96d56Sopenharmony_ci    >>> Global = manager.Namespace()
19117db96d56Sopenharmony_ci    >>> Global.x = 10
19127db96d56Sopenharmony_ci    >>> Global.y = 'hello'
19137db96d56Sopenharmony_ci    >>> Global._z = 12.3    # this is an attribute of the proxy
19147db96d56Sopenharmony_ci    >>> print(Global)
19157db96d56Sopenharmony_ci    Namespace(x=10, y='hello')
19167db96d56Sopenharmony_ci
19177db96d56Sopenharmony_ci
19187db96d56Sopenharmony_ciCustomized managers
19197db96d56Sopenharmony_ci>>>>>>>>>>>>>>>>>>>
19207db96d56Sopenharmony_ci
19217db96d56Sopenharmony_ciTo create one's own manager, one creates a subclass of :class:`BaseManager` and
19227db96d56Sopenharmony_ciuses the :meth:`~BaseManager.register` classmethod to register new types or
19237db96d56Sopenharmony_cicallables with the manager class.  For example::
19247db96d56Sopenharmony_ci
19257db96d56Sopenharmony_ci   from multiprocessing.managers import BaseManager
19267db96d56Sopenharmony_ci
19277db96d56Sopenharmony_ci   class MathsClass:
19287db96d56Sopenharmony_ci       def add(self, x, y):
19297db96d56Sopenharmony_ci           return x + y
19307db96d56Sopenharmony_ci       def mul(self, x, y):
19317db96d56Sopenharmony_ci           return x * y
19327db96d56Sopenharmony_ci
19337db96d56Sopenharmony_ci   class MyManager(BaseManager):
19347db96d56Sopenharmony_ci       pass
19357db96d56Sopenharmony_ci
19367db96d56Sopenharmony_ci   MyManager.register('Maths', MathsClass)
19377db96d56Sopenharmony_ci
19387db96d56Sopenharmony_ci   if __name__ == '__main__':
19397db96d56Sopenharmony_ci       with MyManager() as manager:
19407db96d56Sopenharmony_ci           maths = manager.Maths()
19417db96d56Sopenharmony_ci           print(maths.add(4, 3))         # prints 7
19427db96d56Sopenharmony_ci           print(maths.mul(7, 8))         # prints 56
19437db96d56Sopenharmony_ci
19447db96d56Sopenharmony_ci
19457db96d56Sopenharmony_ciUsing a remote manager
19467db96d56Sopenharmony_ci>>>>>>>>>>>>>>>>>>>>>>
19477db96d56Sopenharmony_ci
19487db96d56Sopenharmony_ciIt is possible to run a manager server on one machine and have clients use it
19497db96d56Sopenharmony_cifrom other machines (assuming that the firewalls involved allow it).
19507db96d56Sopenharmony_ci
19517db96d56Sopenharmony_ciRunning the following commands creates a server for a single shared queue which
19527db96d56Sopenharmony_ciremote clients can access::
19537db96d56Sopenharmony_ci
19547db96d56Sopenharmony_ci   >>> from multiprocessing.managers import BaseManager
19557db96d56Sopenharmony_ci   >>> from queue import Queue
19567db96d56Sopenharmony_ci   >>> queue = Queue()
19577db96d56Sopenharmony_ci   >>> class QueueManager(BaseManager): pass
19587db96d56Sopenharmony_ci   >>> QueueManager.register('get_queue', callable=lambda:queue)
19597db96d56Sopenharmony_ci   >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
19607db96d56Sopenharmony_ci   >>> s = m.get_server()
19617db96d56Sopenharmony_ci   >>> s.serve_forever()
19627db96d56Sopenharmony_ci
19637db96d56Sopenharmony_ciOne client can access the server as follows::
19647db96d56Sopenharmony_ci
19657db96d56Sopenharmony_ci   >>> from multiprocessing.managers import BaseManager
19667db96d56Sopenharmony_ci   >>> class QueueManager(BaseManager): pass
19677db96d56Sopenharmony_ci   >>> QueueManager.register('get_queue')
19687db96d56Sopenharmony_ci   >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
19697db96d56Sopenharmony_ci   >>> m.connect()
19707db96d56Sopenharmony_ci   >>> queue = m.get_queue()
19717db96d56Sopenharmony_ci   >>> queue.put('hello')
19727db96d56Sopenharmony_ci
19737db96d56Sopenharmony_ciAnother client can also use it::
19747db96d56Sopenharmony_ci
19757db96d56Sopenharmony_ci   >>> from multiprocessing.managers import BaseManager
19767db96d56Sopenharmony_ci   >>> class QueueManager(BaseManager): pass
19777db96d56Sopenharmony_ci   >>> QueueManager.register('get_queue')
19787db96d56Sopenharmony_ci   >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
19797db96d56Sopenharmony_ci   >>> m.connect()
19807db96d56Sopenharmony_ci   >>> queue = m.get_queue()
19817db96d56Sopenharmony_ci   >>> queue.get()
19827db96d56Sopenharmony_ci   'hello'
19837db96d56Sopenharmony_ci
19847db96d56Sopenharmony_ciLocal processes can also access that queue, using the code from above on the
19857db96d56Sopenharmony_ciclient to access it remotely::
19867db96d56Sopenharmony_ci
19877db96d56Sopenharmony_ci    >>> from multiprocessing import Process, Queue
19887db96d56Sopenharmony_ci    >>> from multiprocessing.managers import BaseManager
19897db96d56Sopenharmony_ci    >>> class Worker(Process):
19907db96d56Sopenharmony_ci    ...     def __init__(self, q):
19917db96d56Sopenharmony_ci    ...         self.q = q
19927db96d56Sopenharmony_ci    ...         super().__init__()
19937db96d56Sopenharmony_ci    ...     def run(self):
19947db96d56Sopenharmony_ci    ...         self.q.put('local hello')
19957db96d56Sopenharmony_ci    ...
19967db96d56Sopenharmony_ci    >>> queue = Queue()
19977db96d56Sopenharmony_ci    >>> w = Worker(queue)
19987db96d56Sopenharmony_ci    >>> w.start()
19997db96d56Sopenharmony_ci    >>> class QueueManager(BaseManager): pass
20007db96d56Sopenharmony_ci    ...
20017db96d56Sopenharmony_ci    >>> QueueManager.register('get_queue', callable=lambda: queue)
20027db96d56Sopenharmony_ci    >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
20037db96d56Sopenharmony_ci    >>> s = m.get_server()
20047db96d56Sopenharmony_ci    >>> s.serve_forever()
20057db96d56Sopenharmony_ci
20067db96d56Sopenharmony_ci.. _multiprocessing-proxy_objects:
20077db96d56Sopenharmony_ci
20087db96d56Sopenharmony_ciProxy Objects
20097db96d56Sopenharmony_ci~~~~~~~~~~~~~
20107db96d56Sopenharmony_ci
20117db96d56Sopenharmony_ciA proxy is an object which *refers* to a shared object which lives (presumably)
20127db96d56Sopenharmony_ciin a different process.  The shared object is said to be the *referent* of the
20137db96d56Sopenharmony_ciproxy.  Multiple proxy objects may have the same referent.
20147db96d56Sopenharmony_ci
20157db96d56Sopenharmony_ciA proxy object has methods which invoke corresponding methods of its referent
20167db96d56Sopenharmony_ci(although not every method of the referent will necessarily be available through
20177db96d56Sopenharmony_cithe proxy).  In this way, a proxy can be used just like its referent can:
20187db96d56Sopenharmony_ci
20197db96d56Sopenharmony_ci.. doctest::
20207db96d56Sopenharmony_ci
20217db96d56Sopenharmony_ci   >>> from multiprocessing import Manager
20227db96d56Sopenharmony_ci   >>> manager = Manager()
20237db96d56Sopenharmony_ci   >>> l = manager.list([i*i for i in range(10)])
20247db96d56Sopenharmony_ci   >>> print(l)
20257db96d56Sopenharmony_ci   [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
20267db96d56Sopenharmony_ci   >>> print(repr(l))
20277db96d56Sopenharmony_ci   <ListProxy object, typeid 'list' at 0x...>
20287db96d56Sopenharmony_ci   >>> l[4]
20297db96d56Sopenharmony_ci   16
20307db96d56Sopenharmony_ci   >>> l[2:5]
20317db96d56Sopenharmony_ci   [4, 9, 16]
20327db96d56Sopenharmony_ci
20337db96d56Sopenharmony_ciNotice that applying :func:`str` to a proxy will return the representation of
20347db96d56Sopenharmony_cithe referent, whereas applying :func:`repr` will return the representation of
20357db96d56Sopenharmony_cithe proxy.
20367db96d56Sopenharmony_ci
20377db96d56Sopenharmony_ciAn important feature of proxy objects is that they are picklable so they can be
20387db96d56Sopenharmony_cipassed between processes.  As such, a referent can contain
20397db96d56Sopenharmony_ci:ref:`multiprocessing-proxy_objects`.  This permits nesting of these managed
20407db96d56Sopenharmony_cilists, dicts, and other :ref:`multiprocessing-proxy_objects`:
20417db96d56Sopenharmony_ci
20427db96d56Sopenharmony_ci.. doctest::
20437db96d56Sopenharmony_ci
20447db96d56Sopenharmony_ci   >>> a = manager.list()
20457db96d56Sopenharmony_ci   >>> b = manager.list()
20467db96d56Sopenharmony_ci   >>> a.append(b)         # referent of a now contains referent of b
20477db96d56Sopenharmony_ci   >>> print(a, b)
20487db96d56Sopenharmony_ci   [<ListProxy object, typeid 'list' at ...>] []
20497db96d56Sopenharmony_ci   >>> b.append('hello')
20507db96d56Sopenharmony_ci   >>> print(a[0], b)
20517db96d56Sopenharmony_ci   ['hello'] ['hello']
20527db96d56Sopenharmony_ci
20537db96d56Sopenharmony_ciSimilarly, dict and list proxies may be nested inside one another::
20547db96d56Sopenharmony_ci
20557db96d56Sopenharmony_ci   >>> l_outer = manager.list([ manager.dict() for i in range(2) ])
20567db96d56Sopenharmony_ci   >>> d_first_inner = l_outer[0]
20577db96d56Sopenharmony_ci   >>> d_first_inner['a'] = 1
20587db96d56Sopenharmony_ci   >>> d_first_inner['b'] = 2
20597db96d56Sopenharmony_ci   >>> l_outer[1]['c'] = 3
20607db96d56Sopenharmony_ci   >>> l_outer[1]['z'] = 26
20617db96d56Sopenharmony_ci   >>> print(l_outer[0])
20627db96d56Sopenharmony_ci   {'a': 1, 'b': 2}
20637db96d56Sopenharmony_ci   >>> print(l_outer[1])
20647db96d56Sopenharmony_ci   {'c': 3, 'z': 26}
20657db96d56Sopenharmony_ci
20667db96d56Sopenharmony_ciIf standard (non-proxy) :class:`list` or :class:`dict` objects are contained
20677db96d56Sopenharmony_ciin a referent, modifications to those mutable values will not be propagated
20687db96d56Sopenharmony_cithrough the manager because the proxy has no way of knowing when the values
20697db96d56Sopenharmony_cicontained within are modified.  However, storing a value in a container proxy
20707db96d56Sopenharmony_ci(which triggers a ``__setitem__`` on the proxy object) does propagate through
20717db96d56Sopenharmony_cithe manager and so to effectively modify such an item, one could re-assign the
20727db96d56Sopenharmony_cimodified value to the container proxy::
20737db96d56Sopenharmony_ci
20747db96d56Sopenharmony_ci   # create a list proxy and append a mutable object (a dictionary)
20757db96d56Sopenharmony_ci   lproxy = manager.list()
20767db96d56Sopenharmony_ci   lproxy.append({})
20777db96d56Sopenharmony_ci   # now mutate the dictionary
20787db96d56Sopenharmony_ci   d = lproxy[0]
20797db96d56Sopenharmony_ci   d['a'] = 1
20807db96d56Sopenharmony_ci   d['b'] = 2
20817db96d56Sopenharmony_ci   # at this point, the changes to d are not yet synced, but by
20827db96d56Sopenharmony_ci   # updating the dictionary, the proxy is notified of the change
20837db96d56Sopenharmony_ci   lproxy[0] = d
20847db96d56Sopenharmony_ci
20857db96d56Sopenharmony_ciThis approach is perhaps less convenient than employing nested
20867db96d56Sopenharmony_ci:ref:`multiprocessing-proxy_objects` for most use cases but also
20877db96d56Sopenharmony_cidemonstrates a level of control over the synchronization.
20887db96d56Sopenharmony_ci
20897db96d56Sopenharmony_ci.. note::
20907db96d56Sopenharmony_ci
20917db96d56Sopenharmony_ci   The proxy types in :mod:`multiprocessing` do nothing to support comparisons
20927db96d56Sopenharmony_ci   by value.  So, for instance, we have:
20937db96d56Sopenharmony_ci
20947db96d56Sopenharmony_ci   .. doctest::
20957db96d56Sopenharmony_ci
20967db96d56Sopenharmony_ci       >>> manager.list([1,2,3]) == [1,2,3]
20977db96d56Sopenharmony_ci       False
20987db96d56Sopenharmony_ci
20997db96d56Sopenharmony_ci   One should just use a copy of the referent instead when making comparisons.
21007db96d56Sopenharmony_ci
21017db96d56Sopenharmony_ci.. class:: BaseProxy
21027db96d56Sopenharmony_ci
21037db96d56Sopenharmony_ci   Proxy objects are instances of subclasses of :class:`BaseProxy`.
21047db96d56Sopenharmony_ci
21057db96d56Sopenharmony_ci   .. method:: _callmethod(methodname[, args[, kwds]])
21067db96d56Sopenharmony_ci
21077db96d56Sopenharmony_ci      Call and return the result of a method of the proxy's referent.
21087db96d56Sopenharmony_ci
21097db96d56Sopenharmony_ci      If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
21107db96d56Sopenharmony_ci
21117db96d56Sopenharmony_ci         proxy._callmethod(methodname, args, kwds)
21127db96d56Sopenharmony_ci
21137db96d56Sopenharmony_ci      will evaluate the expression ::
21147db96d56Sopenharmony_ci
21157db96d56Sopenharmony_ci         getattr(obj, methodname)(*args, **kwds)
21167db96d56Sopenharmony_ci
21177db96d56Sopenharmony_ci      in the manager's process.
21187db96d56Sopenharmony_ci
21197db96d56Sopenharmony_ci      The returned value will be a copy of the result of the call or a proxy to
21207db96d56Sopenharmony_ci      a new shared object -- see documentation for the *method_to_typeid*
21217db96d56Sopenharmony_ci      argument of :meth:`BaseManager.register`.
21227db96d56Sopenharmony_ci
21237db96d56Sopenharmony_ci      If an exception is raised by the call, then is re-raised by
21247db96d56Sopenharmony_ci      :meth:`_callmethod`.  If some other exception is raised in the manager's
21257db96d56Sopenharmony_ci      process then this is converted into a :exc:`RemoteError` exception and is
21267db96d56Sopenharmony_ci      raised by :meth:`_callmethod`.
21277db96d56Sopenharmony_ci
21287db96d56Sopenharmony_ci      Note in particular that an exception will be raised if *methodname* has
21297db96d56Sopenharmony_ci      not been *exposed*.
21307db96d56Sopenharmony_ci
21317db96d56Sopenharmony_ci      An example of the usage of :meth:`_callmethod`:
21327db96d56Sopenharmony_ci
21337db96d56Sopenharmony_ci      .. doctest::
21347db96d56Sopenharmony_ci
21357db96d56Sopenharmony_ci         >>> l = manager.list(range(10))
21367db96d56Sopenharmony_ci         >>> l._callmethod('__len__')
21377db96d56Sopenharmony_ci         10
21387db96d56Sopenharmony_ci         >>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
21397db96d56Sopenharmony_ci         [2, 3, 4, 5, 6]
21407db96d56Sopenharmony_ci         >>> l._callmethod('__getitem__', (20,))          # equivalent to l[20]
21417db96d56Sopenharmony_ci         Traceback (most recent call last):
21427db96d56Sopenharmony_ci         ...
21437db96d56Sopenharmony_ci         IndexError: list index out of range
21447db96d56Sopenharmony_ci
21457db96d56Sopenharmony_ci   .. method:: _getvalue()
21467db96d56Sopenharmony_ci
21477db96d56Sopenharmony_ci      Return a copy of the referent.
21487db96d56Sopenharmony_ci
21497db96d56Sopenharmony_ci      If the referent is unpicklable then this will raise an exception.
21507db96d56Sopenharmony_ci
21517db96d56Sopenharmony_ci   .. method:: __repr__
21527db96d56Sopenharmony_ci
21537db96d56Sopenharmony_ci      Return a representation of the proxy object.
21547db96d56Sopenharmony_ci
21557db96d56Sopenharmony_ci   .. method:: __str__
21567db96d56Sopenharmony_ci
21577db96d56Sopenharmony_ci      Return the representation of the referent.
21587db96d56Sopenharmony_ci
21597db96d56Sopenharmony_ci
21607db96d56Sopenharmony_ciCleanup
21617db96d56Sopenharmony_ci>>>>>>>
21627db96d56Sopenharmony_ci
21637db96d56Sopenharmony_ciA proxy object uses a weakref callback so that when it gets garbage collected it
21647db96d56Sopenharmony_cideregisters itself from the manager which owns its referent.
21657db96d56Sopenharmony_ci
21667db96d56Sopenharmony_ciA shared object gets deleted from the manager process when there are no longer
21677db96d56Sopenharmony_ciany proxies referring to it.
21687db96d56Sopenharmony_ci
21697db96d56Sopenharmony_ci
21707db96d56Sopenharmony_ciProcess Pools
21717db96d56Sopenharmony_ci~~~~~~~~~~~~~
21727db96d56Sopenharmony_ci
21737db96d56Sopenharmony_ci.. module:: multiprocessing.pool
21747db96d56Sopenharmony_ci   :synopsis: Create pools of processes.
21757db96d56Sopenharmony_ci
21767db96d56Sopenharmony_ciOne can create a pool of processes which will carry out tasks submitted to it
21777db96d56Sopenharmony_ciwith the :class:`Pool` class.
21787db96d56Sopenharmony_ci
21797db96d56Sopenharmony_ci.. class:: Pool([processes[, initializer[, initargs[, maxtasksperchild [, context]]]]])
21807db96d56Sopenharmony_ci
21817db96d56Sopenharmony_ci   A process pool object which controls a pool of worker processes to which jobs
21827db96d56Sopenharmony_ci   can be submitted.  It supports asynchronous results with timeouts and
21837db96d56Sopenharmony_ci   callbacks and has a parallel map implementation.
21847db96d56Sopenharmony_ci
21857db96d56Sopenharmony_ci   *processes* is the number of worker processes to use.  If *processes* is
21867db96d56Sopenharmony_ci   ``None`` then the number returned by :func:`os.cpu_count` is used.
21877db96d56Sopenharmony_ci
21887db96d56Sopenharmony_ci   If *initializer* is not ``None`` then each worker process will call
21897db96d56Sopenharmony_ci   ``initializer(*initargs)`` when it starts.
21907db96d56Sopenharmony_ci
21917db96d56Sopenharmony_ci   *maxtasksperchild* is the number of tasks a worker process can complete
21927db96d56Sopenharmony_ci   before it will exit and be replaced with a fresh worker process, to enable
21937db96d56Sopenharmony_ci   unused resources to be freed. The default *maxtasksperchild* is ``None``, which
21947db96d56Sopenharmony_ci   means worker processes will live as long as the pool.
21957db96d56Sopenharmony_ci
21967db96d56Sopenharmony_ci   *context* can be used to specify the context used for starting
21977db96d56Sopenharmony_ci   the worker processes.  Usually a pool is created using the
21987db96d56Sopenharmony_ci   function :func:`multiprocessing.Pool` or the :meth:`Pool` method
21997db96d56Sopenharmony_ci   of a context object.  In both cases *context* is set
22007db96d56Sopenharmony_ci   appropriately.
22017db96d56Sopenharmony_ci
22027db96d56Sopenharmony_ci   Note that the methods of the pool object should only be called by
22037db96d56Sopenharmony_ci   the process which created the pool.
22047db96d56Sopenharmony_ci
22057db96d56Sopenharmony_ci   .. warning::
22067db96d56Sopenharmony_ci      :class:`multiprocessing.pool` objects have internal resources that need to be
22077db96d56Sopenharmony_ci      properly managed (like any other resource) by using the pool as a context manager
22087db96d56Sopenharmony_ci      or by calling :meth:`close` and :meth:`terminate` manually. Failure to do this
22097db96d56Sopenharmony_ci      can lead to the process hanging on finalization.
22107db96d56Sopenharmony_ci
22117db96d56Sopenharmony_ci      Note that it is **not correct** to rely on the garbage collector to destroy the pool
22127db96d56Sopenharmony_ci      as CPython does not assure that the finalizer of the pool will be called
22137db96d56Sopenharmony_ci      (see :meth:`object.__del__` for more information).
22147db96d56Sopenharmony_ci
22157db96d56Sopenharmony_ci   .. versionadded:: 3.2
22167db96d56Sopenharmony_ci      *maxtasksperchild*
22177db96d56Sopenharmony_ci
22187db96d56Sopenharmony_ci   .. versionadded:: 3.4
22197db96d56Sopenharmony_ci      *context*
22207db96d56Sopenharmony_ci
22217db96d56Sopenharmony_ci   .. note::
22227db96d56Sopenharmony_ci
22237db96d56Sopenharmony_ci      Worker processes within a :class:`Pool` typically live for the complete
22247db96d56Sopenharmony_ci      duration of the Pool's work queue. A frequent pattern found in other
22257db96d56Sopenharmony_ci      systems (such as Apache, mod_wsgi, etc) to free resources held by
22267db96d56Sopenharmony_ci      workers is to allow a worker within a pool to complete only a set
22277db96d56Sopenharmony_ci      amount of work before being exiting, being cleaned up and a new
22287db96d56Sopenharmony_ci      process spawned to replace the old one. The *maxtasksperchild*
22297db96d56Sopenharmony_ci      argument to the :class:`Pool` exposes this ability to the end user.
22307db96d56Sopenharmony_ci
22317db96d56Sopenharmony_ci   .. method:: apply(func[, args[, kwds]])
22327db96d56Sopenharmony_ci
22337db96d56Sopenharmony_ci      Call *func* with arguments *args* and keyword arguments *kwds*.  It blocks
22347db96d56Sopenharmony_ci      until the result is ready. Given this blocks, :meth:`apply_async` is
22357db96d56Sopenharmony_ci      better suited for performing work in parallel. Additionally, *func*
22367db96d56Sopenharmony_ci      is only executed in one of the workers of the pool.
22377db96d56Sopenharmony_ci
22387db96d56Sopenharmony_ci   .. method:: apply_async(func[, args[, kwds[, callback[, error_callback]]]])
22397db96d56Sopenharmony_ci
22407db96d56Sopenharmony_ci      A variant of the :meth:`apply` method which returns a
22417db96d56Sopenharmony_ci      :class:`~multiprocessing.pool.AsyncResult` object.
22427db96d56Sopenharmony_ci
22437db96d56Sopenharmony_ci      If *callback* is specified then it should be a callable which accepts a
22447db96d56Sopenharmony_ci      single argument.  When the result becomes ready *callback* is applied to
22457db96d56Sopenharmony_ci      it, that is unless the call failed, in which case the *error_callback*
22467db96d56Sopenharmony_ci      is applied instead.
22477db96d56Sopenharmony_ci
22487db96d56Sopenharmony_ci      If *error_callback* is specified then it should be a callable which
22497db96d56Sopenharmony_ci      accepts a single argument.  If the target function fails, then
22507db96d56Sopenharmony_ci      the *error_callback* is called with the exception instance.
22517db96d56Sopenharmony_ci
22527db96d56Sopenharmony_ci      Callbacks should complete immediately since otherwise the thread which
22537db96d56Sopenharmony_ci      handles the results will get blocked.
22547db96d56Sopenharmony_ci
22557db96d56Sopenharmony_ci   .. method:: map(func, iterable[, chunksize])
22567db96d56Sopenharmony_ci
22577db96d56Sopenharmony_ci      A parallel equivalent of the :func:`map` built-in function (it supports only
22587db96d56Sopenharmony_ci      one *iterable* argument though, for multiple iterables see :meth:`starmap`).
22597db96d56Sopenharmony_ci      It blocks until the result is ready.
22607db96d56Sopenharmony_ci
22617db96d56Sopenharmony_ci      This method chops the iterable into a number of chunks which it submits to
22627db96d56Sopenharmony_ci      the process pool as separate tasks.  The (approximate) size of these
22637db96d56Sopenharmony_ci      chunks can be specified by setting *chunksize* to a positive integer.
22647db96d56Sopenharmony_ci
22657db96d56Sopenharmony_ci      Note that it may cause high memory usage for very long iterables. Consider
22667db96d56Sopenharmony_ci      using :meth:`imap` or :meth:`imap_unordered` with explicit *chunksize*
22677db96d56Sopenharmony_ci      option for better efficiency.
22687db96d56Sopenharmony_ci
22697db96d56Sopenharmony_ci   .. method:: map_async(func, iterable[, chunksize[, callback[, error_callback]]])
22707db96d56Sopenharmony_ci
22717db96d56Sopenharmony_ci      A variant of the :meth:`.map` method which returns a
22727db96d56Sopenharmony_ci      :class:`~multiprocessing.pool.AsyncResult` object.
22737db96d56Sopenharmony_ci
22747db96d56Sopenharmony_ci      If *callback* is specified then it should be a callable which accepts a
22757db96d56Sopenharmony_ci      single argument.  When the result becomes ready *callback* is applied to
22767db96d56Sopenharmony_ci      it, that is unless the call failed, in which case the *error_callback*
22777db96d56Sopenharmony_ci      is applied instead.
22787db96d56Sopenharmony_ci
22797db96d56Sopenharmony_ci      If *error_callback* is specified then it should be a callable which
22807db96d56Sopenharmony_ci      accepts a single argument.  If the target function fails, then
22817db96d56Sopenharmony_ci      the *error_callback* is called with the exception instance.
22827db96d56Sopenharmony_ci
22837db96d56Sopenharmony_ci      Callbacks should complete immediately since otherwise the thread which
22847db96d56Sopenharmony_ci      handles the results will get blocked.
22857db96d56Sopenharmony_ci
22867db96d56Sopenharmony_ci   .. method:: imap(func, iterable[, chunksize])
22877db96d56Sopenharmony_ci
22887db96d56Sopenharmony_ci      A lazier version of :meth:`.map`.
22897db96d56Sopenharmony_ci
22907db96d56Sopenharmony_ci      The *chunksize* argument is the same as the one used by the :meth:`.map`
22917db96d56Sopenharmony_ci      method.  For very long iterables using a large value for *chunksize* can
22927db96d56Sopenharmony_ci      make the job complete **much** faster than using the default value of
22937db96d56Sopenharmony_ci      ``1``.
22947db96d56Sopenharmony_ci
22957db96d56Sopenharmony_ci      Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
22967db96d56Sopenharmony_ci      returned by the :meth:`imap` method has an optional *timeout* parameter:
22977db96d56Sopenharmony_ci      ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
22987db96d56Sopenharmony_ci      result cannot be returned within *timeout* seconds.
22997db96d56Sopenharmony_ci
23007db96d56Sopenharmony_ci   .. method:: imap_unordered(func, iterable[, chunksize])
23017db96d56Sopenharmony_ci
23027db96d56Sopenharmony_ci      The same as :meth:`imap` except that the ordering of the results from the
23037db96d56Sopenharmony_ci      returned iterator should be considered arbitrary.  (Only when there is
23047db96d56Sopenharmony_ci      only one worker process is the order guaranteed to be "correct".)
23057db96d56Sopenharmony_ci
23067db96d56Sopenharmony_ci   .. method:: starmap(func, iterable[, chunksize])
23077db96d56Sopenharmony_ci
23087db96d56Sopenharmony_ci      Like :meth:`~multiprocessing.pool.Pool.map` except that the
23097db96d56Sopenharmony_ci      elements of the *iterable* are expected to be iterables that are
23107db96d56Sopenharmony_ci      unpacked as arguments.
23117db96d56Sopenharmony_ci
23127db96d56Sopenharmony_ci      Hence an *iterable* of ``[(1,2), (3, 4)]`` results in ``[func(1,2),
23137db96d56Sopenharmony_ci      func(3,4)]``.
23147db96d56Sopenharmony_ci
23157db96d56Sopenharmony_ci      .. versionadded:: 3.3
23167db96d56Sopenharmony_ci
23177db96d56Sopenharmony_ci   .. method:: starmap_async(func, iterable[, chunksize[, callback[, error_callback]]])
23187db96d56Sopenharmony_ci
23197db96d56Sopenharmony_ci      A combination of :meth:`starmap` and :meth:`map_async` that iterates over
23207db96d56Sopenharmony_ci      *iterable* of iterables and calls *func* with the iterables unpacked.
23217db96d56Sopenharmony_ci      Returns a result object.
23227db96d56Sopenharmony_ci
23237db96d56Sopenharmony_ci      .. versionadded:: 3.3
23247db96d56Sopenharmony_ci
23257db96d56Sopenharmony_ci   .. method:: close()
23267db96d56Sopenharmony_ci
23277db96d56Sopenharmony_ci      Prevents any more tasks from being submitted to the pool.  Once all the
23287db96d56Sopenharmony_ci      tasks have been completed the worker processes will exit.
23297db96d56Sopenharmony_ci
23307db96d56Sopenharmony_ci   .. method:: terminate()
23317db96d56Sopenharmony_ci
23327db96d56Sopenharmony_ci      Stops the worker processes immediately without completing outstanding
23337db96d56Sopenharmony_ci      work.  When the pool object is garbage collected :meth:`terminate` will be
23347db96d56Sopenharmony_ci      called immediately.
23357db96d56Sopenharmony_ci
23367db96d56Sopenharmony_ci   .. method:: join()
23377db96d56Sopenharmony_ci
23387db96d56Sopenharmony_ci      Wait for the worker processes to exit.  One must call :meth:`close` or
23397db96d56Sopenharmony_ci      :meth:`terminate` before using :meth:`join`.
23407db96d56Sopenharmony_ci
23417db96d56Sopenharmony_ci   .. versionadded:: 3.3
23427db96d56Sopenharmony_ci      Pool objects now support the context management protocol -- see
23437db96d56Sopenharmony_ci      :ref:`typecontextmanager`.  :meth:`~contextmanager.__enter__` returns the
23447db96d56Sopenharmony_ci      pool object, and :meth:`~contextmanager.__exit__` calls :meth:`terminate`.
23457db96d56Sopenharmony_ci
23467db96d56Sopenharmony_ci
23477db96d56Sopenharmony_ci.. class:: AsyncResult
23487db96d56Sopenharmony_ci
23497db96d56Sopenharmony_ci   The class of the result returned by :meth:`Pool.apply_async` and
23507db96d56Sopenharmony_ci   :meth:`Pool.map_async`.
23517db96d56Sopenharmony_ci
23527db96d56Sopenharmony_ci   .. method:: get([timeout])
23537db96d56Sopenharmony_ci
23547db96d56Sopenharmony_ci      Return the result when it arrives.  If *timeout* is not ``None`` and the
23557db96d56Sopenharmony_ci      result does not arrive within *timeout* seconds then
23567db96d56Sopenharmony_ci      :exc:`multiprocessing.TimeoutError` is raised.  If the remote call raised
23577db96d56Sopenharmony_ci      an exception then that exception will be reraised by :meth:`get`.
23587db96d56Sopenharmony_ci
23597db96d56Sopenharmony_ci   .. method:: wait([timeout])
23607db96d56Sopenharmony_ci
23617db96d56Sopenharmony_ci      Wait until the result is available or until *timeout* seconds pass.
23627db96d56Sopenharmony_ci
23637db96d56Sopenharmony_ci   .. method:: ready()
23647db96d56Sopenharmony_ci
23657db96d56Sopenharmony_ci      Return whether the call has completed.
23667db96d56Sopenharmony_ci
23677db96d56Sopenharmony_ci   .. method:: successful()
23687db96d56Sopenharmony_ci
23697db96d56Sopenharmony_ci      Return whether the call completed without raising an exception.  Will
23707db96d56Sopenharmony_ci      raise :exc:`ValueError` if the result is not ready.
23717db96d56Sopenharmony_ci
23727db96d56Sopenharmony_ci      .. versionchanged:: 3.7
23737db96d56Sopenharmony_ci         If the result is not ready, :exc:`ValueError` is raised instead of
23747db96d56Sopenharmony_ci         :exc:`AssertionError`.
23757db96d56Sopenharmony_ci
23767db96d56Sopenharmony_ciThe following example demonstrates the use of a pool::
23777db96d56Sopenharmony_ci
23787db96d56Sopenharmony_ci   from multiprocessing import Pool
23797db96d56Sopenharmony_ci   import time
23807db96d56Sopenharmony_ci
23817db96d56Sopenharmony_ci   def f(x):
23827db96d56Sopenharmony_ci       return x*x
23837db96d56Sopenharmony_ci
23847db96d56Sopenharmony_ci   if __name__ == '__main__':
23857db96d56Sopenharmony_ci       with Pool(processes=4) as pool:         # start 4 worker processes
23867db96d56Sopenharmony_ci           result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
23877db96d56Sopenharmony_ci           print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow
23887db96d56Sopenharmony_ci
23897db96d56Sopenharmony_ci           print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"
23907db96d56Sopenharmony_ci
23917db96d56Sopenharmony_ci           it = pool.imap(f, range(10))
23927db96d56Sopenharmony_ci           print(next(it))                     # prints "0"
23937db96d56Sopenharmony_ci           print(next(it))                     # prints "1"
23947db96d56Sopenharmony_ci           print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow
23957db96d56Sopenharmony_ci
23967db96d56Sopenharmony_ci           result = pool.apply_async(time.sleep, (10,))
23977db96d56Sopenharmony_ci           print(result.get(timeout=1))        # raises multiprocessing.TimeoutError
23987db96d56Sopenharmony_ci
23997db96d56Sopenharmony_ci
24007db96d56Sopenharmony_ci.. _multiprocessing-listeners-clients:
24017db96d56Sopenharmony_ci
24027db96d56Sopenharmony_ciListeners and Clients
24037db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~
24047db96d56Sopenharmony_ci
24057db96d56Sopenharmony_ci.. module:: multiprocessing.connection
24067db96d56Sopenharmony_ci   :synopsis: API for dealing with sockets.
24077db96d56Sopenharmony_ci
24087db96d56Sopenharmony_ciUsually message passing between processes is done using queues or by using
24097db96d56Sopenharmony_ci:class:`~Connection` objects returned by
24107db96d56Sopenharmony_ci:func:`~multiprocessing.Pipe`.
24117db96d56Sopenharmony_ci
24127db96d56Sopenharmony_ciHowever, the :mod:`multiprocessing.connection` module allows some extra
24137db96d56Sopenharmony_ciflexibility.  It basically gives a high level message oriented API for dealing
24147db96d56Sopenharmony_ciwith sockets or Windows named pipes.  It also has support for *digest
24157db96d56Sopenharmony_ciauthentication* using the :mod:`hmac` module, and for polling
24167db96d56Sopenharmony_cimultiple connections at the same time.
24177db96d56Sopenharmony_ci
24187db96d56Sopenharmony_ci
24197db96d56Sopenharmony_ci.. function:: deliver_challenge(connection, authkey)
24207db96d56Sopenharmony_ci
24217db96d56Sopenharmony_ci   Send a randomly generated message to the other end of the connection and wait
24227db96d56Sopenharmony_ci   for a reply.
24237db96d56Sopenharmony_ci
24247db96d56Sopenharmony_ci   If the reply matches the digest of the message using *authkey* as the key
24257db96d56Sopenharmony_ci   then a welcome message is sent to the other end of the connection.  Otherwise
24267db96d56Sopenharmony_ci   :exc:`~multiprocessing.AuthenticationError` is raised.
24277db96d56Sopenharmony_ci
24287db96d56Sopenharmony_ci.. function:: answer_challenge(connection, authkey)
24297db96d56Sopenharmony_ci
24307db96d56Sopenharmony_ci   Receive a message, calculate the digest of the message using *authkey* as the
24317db96d56Sopenharmony_ci   key, and then send the digest back.
24327db96d56Sopenharmony_ci
24337db96d56Sopenharmony_ci   If a welcome message is not received, then
24347db96d56Sopenharmony_ci   :exc:`~multiprocessing.AuthenticationError` is raised.
24357db96d56Sopenharmony_ci
24367db96d56Sopenharmony_ci.. function:: Client(address[, family[, authkey]])
24377db96d56Sopenharmony_ci
24387db96d56Sopenharmony_ci   Attempt to set up a connection to the listener which is using address
24397db96d56Sopenharmony_ci   *address*, returning a :class:`~Connection`.
24407db96d56Sopenharmony_ci
24417db96d56Sopenharmony_ci   The type of the connection is determined by *family* argument, but this can
24427db96d56Sopenharmony_ci   generally be omitted since it can usually be inferred from the format of
24437db96d56Sopenharmony_ci   *address*. (See :ref:`multiprocessing-address-formats`)
24447db96d56Sopenharmony_ci
24457db96d56Sopenharmony_ci   If *authkey* is given and not None, it should be a byte string and will be
24467db96d56Sopenharmony_ci   used as the secret key for an HMAC-based authentication challenge. No
24477db96d56Sopenharmony_ci   authentication is done if *authkey* is None.
24487db96d56Sopenharmony_ci   :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails.
24497db96d56Sopenharmony_ci   See :ref:`multiprocessing-auth-keys`.
24507db96d56Sopenharmony_ci
24517db96d56Sopenharmony_ci.. class:: Listener([address[, family[, backlog[, authkey]]]])
24527db96d56Sopenharmony_ci
24537db96d56Sopenharmony_ci   A wrapper for a bound socket or Windows named pipe which is 'listening' for
24547db96d56Sopenharmony_ci   connections.
24557db96d56Sopenharmony_ci
24567db96d56Sopenharmony_ci   *address* is the address to be used by the bound socket or named pipe of the
24577db96d56Sopenharmony_ci   listener object.
24587db96d56Sopenharmony_ci
24597db96d56Sopenharmony_ci   .. note::
24607db96d56Sopenharmony_ci
24617db96d56Sopenharmony_ci      If an address of '0.0.0.0' is used, the address will not be a connectable
24627db96d56Sopenharmony_ci      end point on Windows. If you require a connectable end-point,
24637db96d56Sopenharmony_ci      you should use '127.0.0.1'.
24647db96d56Sopenharmony_ci
24657db96d56Sopenharmony_ci   *family* is the type of socket (or named pipe) to use.  This can be one of
24667db96d56Sopenharmony_ci   the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
24677db96d56Sopenharmony_ci   domain socket) or ``'AF_PIPE'`` (for a Windows named pipe).  Of these only
24687db96d56Sopenharmony_ci   the first is guaranteed to be available.  If *family* is ``None`` then the
24697db96d56Sopenharmony_ci   family is inferred from the format of *address*.  If *address* is also
24707db96d56Sopenharmony_ci   ``None`` then a default is chosen.  This default is the family which is
24717db96d56Sopenharmony_ci   assumed to be the fastest available.  See
24727db96d56Sopenharmony_ci   :ref:`multiprocessing-address-formats`.  Note that if *family* is
24737db96d56Sopenharmony_ci   ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
24747db96d56Sopenharmony_ci   private temporary directory created using :func:`tempfile.mkstemp`.
24757db96d56Sopenharmony_ci
24767db96d56Sopenharmony_ci   If the listener object uses a socket then *backlog* (1 by default) is passed
24777db96d56Sopenharmony_ci   to the :meth:`~socket.socket.listen` method of the socket once it has been
24787db96d56Sopenharmony_ci   bound.
24797db96d56Sopenharmony_ci
24807db96d56Sopenharmony_ci   If *authkey* is given and not None, it should be a byte string and will be
24817db96d56Sopenharmony_ci   used as the secret key for an HMAC-based authentication challenge. No
24827db96d56Sopenharmony_ci   authentication is done if *authkey* is None.
24837db96d56Sopenharmony_ci   :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails.
24847db96d56Sopenharmony_ci   See :ref:`multiprocessing-auth-keys`.
24857db96d56Sopenharmony_ci
24867db96d56Sopenharmony_ci   .. method:: accept()
24877db96d56Sopenharmony_ci
24887db96d56Sopenharmony_ci      Accept a connection on the bound socket or named pipe of the listener
24897db96d56Sopenharmony_ci      object and return a :class:`~Connection` object.
24907db96d56Sopenharmony_ci      If authentication is attempted and fails, then
24917db96d56Sopenharmony_ci      :exc:`~multiprocessing.AuthenticationError` is raised.
24927db96d56Sopenharmony_ci
24937db96d56Sopenharmony_ci   .. method:: close()
24947db96d56Sopenharmony_ci
24957db96d56Sopenharmony_ci      Close the bound socket or named pipe of the listener object.  This is
24967db96d56Sopenharmony_ci      called automatically when the listener is garbage collected.  However it
24977db96d56Sopenharmony_ci      is advisable to call it explicitly.
24987db96d56Sopenharmony_ci
24997db96d56Sopenharmony_ci   Listener objects have the following read-only properties:
25007db96d56Sopenharmony_ci
25017db96d56Sopenharmony_ci   .. attribute:: address
25027db96d56Sopenharmony_ci
25037db96d56Sopenharmony_ci      The address which is being used by the Listener object.
25047db96d56Sopenharmony_ci
25057db96d56Sopenharmony_ci   .. attribute:: last_accepted
25067db96d56Sopenharmony_ci
25077db96d56Sopenharmony_ci      The address from which the last accepted connection came.  If this is
25087db96d56Sopenharmony_ci      unavailable then it is ``None``.
25097db96d56Sopenharmony_ci
25107db96d56Sopenharmony_ci   .. versionadded:: 3.3
25117db96d56Sopenharmony_ci      Listener objects now support the context management protocol -- see
25127db96d56Sopenharmony_ci      :ref:`typecontextmanager`.  :meth:`~contextmanager.__enter__` returns the
25137db96d56Sopenharmony_ci      listener object, and :meth:`~contextmanager.__exit__` calls :meth:`close`.
25147db96d56Sopenharmony_ci
25157db96d56Sopenharmony_ci.. function:: wait(object_list, timeout=None)
25167db96d56Sopenharmony_ci
25177db96d56Sopenharmony_ci   Wait till an object in *object_list* is ready.  Returns the list of
25187db96d56Sopenharmony_ci   those objects in *object_list* which are ready.  If *timeout* is a
25197db96d56Sopenharmony_ci   float then the call blocks for at most that many seconds.  If
25207db96d56Sopenharmony_ci   *timeout* is ``None`` then it will block for an unlimited period.
25217db96d56Sopenharmony_ci   A negative timeout is equivalent to a zero timeout.
25227db96d56Sopenharmony_ci
25237db96d56Sopenharmony_ci   For both Unix and Windows, an object can appear in *object_list* if
25247db96d56Sopenharmony_ci   it is
25257db96d56Sopenharmony_ci
25267db96d56Sopenharmony_ci   * a readable :class:`~multiprocessing.connection.Connection` object;
25277db96d56Sopenharmony_ci   * a connected and readable :class:`socket.socket` object; or
25287db96d56Sopenharmony_ci   * the :attr:`~multiprocessing.Process.sentinel` attribute of a
25297db96d56Sopenharmony_ci     :class:`~multiprocessing.Process` object.
25307db96d56Sopenharmony_ci
25317db96d56Sopenharmony_ci   A connection or socket object is ready when there is data available
25327db96d56Sopenharmony_ci   to be read from it, or the other end has been closed.
25337db96d56Sopenharmony_ci
25347db96d56Sopenharmony_ci   **Unix**: ``wait(object_list, timeout)`` almost equivalent
25357db96d56Sopenharmony_ci   ``select.select(object_list, [], [], timeout)``.  The difference is
25367db96d56Sopenharmony_ci   that, if :func:`select.select` is interrupted by a signal, it can
25377db96d56Sopenharmony_ci   raise :exc:`OSError` with an error number of ``EINTR``, whereas
25387db96d56Sopenharmony_ci   :func:`wait` will not.
25397db96d56Sopenharmony_ci
25407db96d56Sopenharmony_ci   **Windows**: An item in *object_list* must either be an integer
25417db96d56Sopenharmony_ci   handle which is waitable (according to the definition used by the
25427db96d56Sopenharmony_ci   documentation of the Win32 function ``WaitForMultipleObjects()``)
25437db96d56Sopenharmony_ci   or it can be an object with a :meth:`fileno` method which returns a
25447db96d56Sopenharmony_ci   socket handle or pipe handle.  (Note that pipe handles and socket
25457db96d56Sopenharmony_ci   handles are **not** waitable handles.)
25467db96d56Sopenharmony_ci
25477db96d56Sopenharmony_ci   .. versionadded:: 3.3
25487db96d56Sopenharmony_ci
25497db96d56Sopenharmony_ci
25507db96d56Sopenharmony_ci**Examples**
25517db96d56Sopenharmony_ci
25527db96d56Sopenharmony_ciThe following server code creates a listener which uses ``'secret password'`` as
25537db96d56Sopenharmony_cian authentication key.  It then waits for a connection and sends some data to
25547db96d56Sopenharmony_cithe client::
25557db96d56Sopenharmony_ci
25567db96d56Sopenharmony_ci   from multiprocessing.connection import Listener
25577db96d56Sopenharmony_ci   from array import array
25587db96d56Sopenharmony_ci
25597db96d56Sopenharmony_ci   address = ('localhost', 6000)     # family is deduced to be 'AF_INET'
25607db96d56Sopenharmony_ci
25617db96d56Sopenharmony_ci   with Listener(address, authkey=b'secret password') as listener:
25627db96d56Sopenharmony_ci       with listener.accept() as conn:
25637db96d56Sopenharmony_ci           print('connection accepted from', listener.last_accepted)
25647db96d56Sopenharmony_ci
25657db96d56Sopenharmony_ci           conn.send([2.25, None, 'junk', float])
25667db96d56Sopenharmony_ci
25677db96d56Sopenharmony_ci           conn.send_bytes(b'hello')
25687db96d56Sopenharmony_ci
25697db96d56Sopenharmony_ci           conn.send_bytes(array('i', [42, 1729]))
25707db96d56Sopenharmony_ci
25717db96d56Sopenharmony_ciThe following code connects to the server and receives some data from the
25727db96d56Sopenharmony_ciserver::
25737db96d56Sopenharmony_ci
25747db96d56Sopenharmony_ci   from multiprocessing.connection import Client
25757db96d56Sopenharmony_ci   from array import array
25767db96d56Sopenharmony_ci
25777db96d56Sopenharmony_ci   address = ('localhost', 6000)
25787db96d56Sopenharmony_ci
25797db96d56Sopenharmony_ci   with Client(address, authkey=b'secret password') as conn:
25807db96d56Sopenharmony_ci       print(conn.recv())                  # => [2.25, None, 'junk', float]
25817db96d56Sopenharmony_ci
25827db96d56Sopenharmony_ci       print(conn.recv_bytes())            # => 'hello'
25837db96d56Sopenharmony_ci
25847db96d56Sopenharmony_ci       arr = array('i', [0, 0, 0, 0, 0])
25857db96d56Sopenharmony_ci       print(conn.recv_bytes_into(arr))    # => 8
25867db96d56Sopenharmony_ci       print(arr)                          # => array('i', [42, 1729, 0, 0, 0])
25877db96d56Sopenharmony_ci
25887db96d56Sopenharmony_ciThe following code uses :func:`~multiprocessing.connection.wait` to
25897db96d56Sopenharmony_ciwait for messages from multiple processes at once::
25907db96d56Sopenharmony_ci
25917db96d56Sopenharmony_ci   import time, random
25927db96d56Sopenharmony_ci   from multiprocessing import Process, Pipe, current_process
25937db96d56Sopenharmony_ci   from multiprocessing.connection import wait
25947db96d56Sopenharmony_ci
25957db96d56Sopenharmony_ci   def foo(w):
25967db96d56Sopenharmony_ci       for i in range(10):
25977db96d56Sopenharmony_ci           w.send((i, current_process().name))
25987db96d56Sopenharmony_ci       w.close()
25997db96d56Sopenharmony_ci
26007db96d56Sopenharmony_ci   if __name__ == '__main__':
26017db96d56Sopenharmony_ci       readers = []
26027db96d56Sopenharmony_ci
26037db96d56Sopenharmony_ci       for i in range(4):
26047db96d56Sopenharmony_ci           r, w = Pipe(duplex=False)
26057db96d56Sopenharmony_ci           readers.append(r)
26067db96d56Sopenharmony_ci           p = Process(target=foo, args=(w,))
26077db96d56Sopenharmony_ci           p.start()
26087db96d56Sopenharmony_ci           # We close the writable end of the pipe now to be sure that
26097db96d56Sopenharmony_ci           # p is the only process which owns a handle for it.  This
26107db96d56Sopenharmony_ci           # ensures that when p closes its handle for the writable end,
26117db96d56Sopenharmony_ci           # wait() will promptly report the readable end as being ready.
26127db96d56Sopenharmony_ci           w.close()
26137db96d56Sopenharmony_ci
26147db96d56Sopenharmony_ci       while readers:
26157db96d56Sopenharmony_ci           for r in wait(readers):
26167db96d56Sopenharmony_ci               try:
26177db96d56Sopenharmony_ci                   msg = r.recv()
26187db96d56Sopenharmony_ci               except EOFError:
26197db96d56Sopenharmony_ci                   readers.remove(r)
26207db96d56Sopenharmony_ci               else:
26217db96d56Sopenharmony_ci                   print(msg)
26227db96d56Sopenharmony_ci
26237db96d56Sopenharmony_ci
26247db96d56Sopenharmony_ci.. _multiprocessing-address-formats:
26257db96d56Sopenharmony_ci
26267db96d56Sopenharmony_ciAddress Formats
26277db96d56Sopenharmony_ci>>>>>>>>>>>>>>>
26287db96d56Sopenharmony_ci
26297db96d56Sopenharmony_ci* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
26307db96d56Sopenharmony_ci  *hostname* is a string and *port* is an integer.
26317db96d56Sopenharmony_ci
26327db96d56Sopenharmony_ci* An ``'AF_UNIX'`` address is a string representing a filename on the
26337db96d56Sopenharmony_ci  filesystem.
26347db96d56Sopenharmony_ci
26357db96d56Sopenharmony_ci* An ``'AF_PIPE'`` address is a string of the form
26367db96d56Sopenharmony_ci  :samp:`r'\\\\\\.\\pipe\\\\{PipeName}'`.  To use :func:`Client` to connect to a named
26377db96d56Sopenharmony_ci  pipe on a remote computer called *ServerName* one should use an address of the
26387db96d56Sopenharmony_ci  form :samp:`r'\\\\\\\\{ServerName}\\pipe\\\\{PipeName}'` instead.
26397db96d56Sopenharmony_ci
26407db96d56Sopenharmony_ciNote that any string beginning with two backslashes is assumed by default to be
26417db96d56Sopenharmony_cian ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
26427db96d56Sopenharmony_ci
26437db96d56Sopenharmony_ci
26447db96d56Sopenharmony_ci.. _multiprocessing-auth-keys:
26457db96d56Sopenharmony_ci
26467db96d56Sopenharmony_ciAuthentication keys
26477db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~
26487db96d56Sopenharmony_ci
26497db96d56Sopenharmony_ciWhen one uses :meth:`Connection.recv <Connection.recv>`, the
26507db96d56Sopenharmony_cidata received is automatically
26517db96d56Sopenharmony_ciunpickled. Unfortunately unpickling data from an untrusted source is a security
26527db96d56Sopenharmony_cirisk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
26537db96d56Sopenharmony_cito provide digest authentication.
26547db96d56Sopenharmony_ci
26557db96d56Sopenharmony_ciAn authentication key is a byte string which can be thought of as a
26567db96d56Sopenharmony_cipassword: once a connection is established both ends will demand proof
26577db96d56Sopenharmony_cithat the other knows the authentication key.  (Demonstrating that both
26587db96d56Sopenharmony_ciends are using the same key does **not** involve sending the key over
26597db96d56Sopenharmony_cithe connection.)
26607db96d56Sopenharmony_ci
26617db96d56Sopenharmony_ciIf authentication is requested but no authentication key is specified then the
26627db96d56Sopenharmony_cireturn value of ``current_process().authkey`` is used (see
26637db96d56Sopenharmony_ci:class:`~multiprocessing.Process`).  This value will be automatically inherited by
26647db96d56Sopenharmony_ciany :class:`~multiprocessing.Process` object that the current process creates.
26657db96d56Sopenharmony_ciThis means that (by default) all processes of a multi-process program will share
26667db96d56Sopenharmony_cia single authentication key which can be used when setting up connections
26677db96d56Sopenharmony_cibetween themselves.
26687db96d56Sopenharmony_ci
26697db96d56Sopenharmony_ciSuitable authentication keys can also be generated by using :func:`os.urandom`.
26707db96d56Sopenharmony_ci
26717db96d56Sopenharmony_ci
26727db96d56Sopenharmony_ciLogging
26737db96d56Sopenharmony_ci~~~~~~~
26747db96d56Sopenharmony_ci
26757db96d56Sopenharmony_ciSome support for logging is available.  Note, however, that the :mod:`logging`
26767db96d56Sopenharmony_cipackage does not use process shared locks so it is possible (depending on the
26777db96d56Sopenharmony_cihandler type) for messages from different processes to get mixed up.
26787db96d56Sopenharmony_ci
26797db96d56Sopenharmony_ci.. currentmodule:: multiprocessing
26807db96d56Sopenharmony_ci.. function:: get_logger()
26817db96d56Sopenharmony_ci
26827db96d56Sopenharmony_ci   Returns the logger used by :mod:`multiprocessing`.  If necessary, a new one
26837db96d56Sopenharmony_ci   will be created.
26847db96d56Sopenharmony_ci
26857db96d56Sopenharmony_ci   When first created the logger has level :data:`logging.NOTSET` and no
26867db96d56Sopenharmony_ci   default handler. Messages sent to this logger will not by default propagate
26877db96d56Sopenharmony_ci   to the root logger.
26887db96d56Sopenharmony_ci
26897db96d56Sopenharmony_ci   Note that on Windows child processes will only inherit the level of the
26907db96d56Sopenharmony_ci   parent process's logger -- any other customization of the logger will not be
26917db96d56Sopenharmony_ci   inherited.
26927db96d56Sopenharmony_ci
26937db96d56Sopenharmony_ci.. currentmodule:: multiprocessing
26947db96d56Sopenharmony_ci.. function:: log_to_stderr(level=None)
26957db96d56Sopenharmony_ci
26967db96d56Sopenharmony_ci   This function performs a call to :func:`get_logger` but in addition to
26977db96d56Sopenharmony_ci   returning the logger created by get_logger, it adds a handler which sends
26987db96d56Sopenharmony_ci   output to :data:`sys.stderr` using format
26997db96d56Sopenharmony_ci   ``'[%(levelname)s/%(processName)s] %(message)s'``.
27007db96d56Sopenharmony_ci   You can modify ``levelname`` of the logger by passing a ``level`` argument.
27017db96d56Sopenharmony_ci
27027db96d56Sopenharmony_ciBelow is an example session with logging turned on::
27037db96d56Sopenharmony_ci
27047db96d56Sopenharmony_ci    >>> import multiprocessing, logging
27057db96d56Sopenharmony_ci    >>> logger = multiprocessing.log_to_stderr()
27067db96d56Sopenharmony_ci    >>> logger.setLevel(logging.INFO)
27077db96d56Sopenharmony_ci    >>> logger.warning('doomed')
27087db96d56Sopenharmony_ci    [WARNING/MainProcess] doomed
27097db96d56Sopenharmony_ci    >>> m = multiprocessing.Manager()
27107db96d56Sopenharmony_ci    [INFO/SyncManager-...] child process calling self.run()
27117db96d56Sopenharmony_ci    [INFO/SyncManager-...] created temp directory /.../pymp-...
27127db96d56Sopenharmony_ci    [INFO/SyncManager-...] manager serving at '/.../listener-...'
27137db96d56Sopenharmony_ci    >>> del m
27147db96d56Sopenharmony_ci    [INFO/MainProcess] sending shutdown message to manager
27157db96d56Sopenharmony_ci    [INFO/SyncManager-...] manager exiting with exitcode 0
27167db96d56Sopenharmony_ci
27177db96d56Sopenharmony_ciFor a full table of logging levels, see the :mod:`logging` module.
27187db96d56Sopenharmony_ci
27197db96d56Sopenharmony_ci
27207db96d56Sopenharmony_ciThe :mod:`multiprocessing.dummy` module
27217db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
27227db96d56Sopenharmony_ci
27237db96d56Sopenharmony_ci.. module:: multiprocessing.dummy
27247db96d56Sopenharmony_ci   :synopsis: Dumb wrapper around threading.
27257db96d56Sopenharmony_ci
27267db96d56Sopenharmony_ci:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
27277db96d56Sopenharmony_cino more than a wrapper around the :mod:`threading` module.
27287db96d56Sopenharmony_ci
27297db96d56Sopenharmony_ci.. currentmodule:: multiprocessing.pool
27307db96d56Sopenharmony_ci
27317db96d56Sopenharmony_ciIn particular, the ``Pool`` function provided by :mod:`multiprocessing.dummy`
27327db96d56Sopenharmony_cireturns an instance of :class:`ThreadPool`, which is a subclass of
27337db96d56Sopenharmony_ci:class:`Pool` that supports all the same method calls but uses a pool of
27347db96d56Sopenharmony_ciworker threads rather than worker processes.
27357db96d56Sopenharmony_ci
27367db96d56Sopenharmony_ci
27377db96d56Sopenharmony_ci.. class:: ThreadPool([processes[, initializer[, initargs]]])
27387db96d56Sopenharmony_ci
27397db96d56Sopenharmony_ci   A thread pool object which controls a pool of worker threads to which jobs
27407db96d56Sopenharmony_ci   can be submitted.  :class:`ThreadPool` instances are fully interface
27417db96d56Sopenharmony_ci   compatible with :class:`Pool` instances, and their resources must also be
27427db96d56Sopenharmony_ci   properly managed, either by using the pool as a context manager or by
27437db96d56Sopenharmony_ci   calling :meth:`~multiprocessing.pool.Pool.close` and
27447db96d56Sopenharmony_ci   :meth:`~multiprocessing.pool.Pool.terminate` manually.
27457db96d56Sopenharmony_ci
27467db96d56Sopenharmony_ci   *processes* is the number of worker threads to use.  If *processes* is
27477db96d56Sopenharmony_ci   ``None`` then the number returned by :func:`os.cpu_count` is used.
27487db96d56Sopenharmony_ci
27497db96d56Sopenharmony_ci   If *initializer* is not ``None`` then each worker process will call
27507db96d56Sopenharmony_ci   ``initializer(*initargs)`` when it starts.
27517db96d56Sopenharmony_ci
27527db96d56Sopenharmony_ci   Unlike :class:`Pool`, *maxtasksperchild* and *context* cannot be provided.
27537db96d56Sopenharmony_ci
27547db96d56Sopenharmony_ci    .. note::
27557db96d56Sopenharmony_ci
27567db96d56Sopenharmony_ci        A :class:`ThreadPool` shares the same interface as :class:`Pool`, which
27577db96d56Sopenharmony_ci        is designed around a pool of processes and predates the introduction of
27587db96d56Sopenharmony_ci        the :class:`concurrent.futures` module.  As such, it inherits some
27597db96d56Sopenharmony_ci        operations that don't make sense for a pool backed by threads, and it
27607db96d56Sopenharmony_ci        has its own type for representing the status of asynchronous jobs,
27617db96d56Sopenharmony_ci        :class:`AsyncResult`, that is not understood by any other libraries.
27627db96d56Sopenharmony_ci
27637db96d56Sopenharmony_ci        Users should generally prefer to use
27647db96d56Sopenharmony_ci        :class:`concurrent.futures.ThreadPoolExecutor`, which has a simpler
27657db96d56Sopenharmony_ci        interface that was designed around threads from the start, and which
27667db96d56Sopenharmony_ci        returns :class:`concurrent.futures.Future` instances that are
27677db96d56Sopenharmony_ci        compatible with many other libraries, including :mod:`asyncio`.
27687db96d56Sopenharmony_ci
27697db96d56Sopenharmony_ci
27707db96d56Sopenharmony_ci.. _multiprocessing-programming:
27717db96d56Sopenharmony_ci
27727db96d56Sopenharmony_ciProgramming guidelines
27737db96d56Sopenharmony_ci----------------------
27747db96d56Sopenharmony_ci
27757db96d56Sopenharmony_ciThere are certain guidelines and idioms which should be adhered to when using
27767db96d56Sopenharmony_ci:mod:`multiprocessing`.
27777db96d56Sopenharmony_ci
27787db96d56Sopenharmony_ci
27797db96d56Sopenharmony_ciAll start methods
27807db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~
27817db96d56Sopenharmony_ci
27827db96d56Sopenharmony_ciThe following applies to all start methods.
27837db96d56Sopenharmony_ci
27847db96d56Sopenharmony_ciAvoid shared state
27857db96d56Sopenharmony_ci
27867db96d56Sopenharmony_ci    As far as possible one should try to avoid shifting large amounts of data
27877db96d56Sopenharmony_ci    between processes.
27887db96d56Sopenharmony_ci
27897db96d56Sopenharmony_ci    It is probably best to stick to using queues or pipes for communication
27907db96d56Sopenharmony_ci    between processes rather than using the lower level synchronization
27917db96d56Sopenharmony_ci    primitives.
27927db96d56Sopenharmony_ci
27937db96d56Sopenharmony_ciPicklability
27947db96d56Sopenharmony_ci
27957db96d56Sopenharmony_ci    Ensure that the arguments to the methods of proxies are picklable.
27967db96d56Sopenharmony_ci
27977db96d56Sopenharmony_ciThread safety of proxies
27987db96d56Sopenharmony_ci
27997db96d56Sopenharmony_ci    Do not use a proxy object from more than one thread unless you protect it
28007db96d56Sopenharmony_ci    with a lock.
28017db96d56Sopenharmony_ci
28027db96d56Sopenharmony_ci    (There is never a problem with different processes using the *same* proxy.)
28037db96d56Sopenharmony_ci
28047db96d56Sopenharmony_ciJoining zombie processes
28057db96d56Sopenharmony_ci
28067db96d56Sopenharmony_ci    On Unix when a process finishes but has not been joined it becomes a zombie.
28077db96d56Sopenharmony_ci    There should never be very many because each time a new process starts (or
28087db96d56Sopenharmony_ci    :func:`~multiprocessing.active_children` is called) all completed processes
28097db96d56Sopenharmony_ci    which have not yet been joined will be joined.  Also calling a finished
28107db96d56Sopenharmony_ci    process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
28117db96d56Sopenharmony_ci    join the process.  Even so it is probably good
28127db96d56Sopenharmony_ci    practice to explicitly join all the processes that you start.
28137db96d56Sopenharmony_ci
28147db96d56Sopenharmony_ciBetter to inherit than pickle/unpickle
28157db96d56Sopenharmony_ci
28167db96d56Sopenharmony_ci    When using the *spawn* or *forkserver* start methods many types
28177db96d56Sopenharmony_ci    from :mod:`multiprocessing` need to be picklable so that child
28187db96d56Sopenharmony_ci    processes can use them.  However, one should generally avoid
28197db96d56Sopenharmony_ci    sending shared objects to other processes using pipes or queues.
28207db96d56Sopenharmony_ci    Instead you should arrange the program so that a process which
28217db96d56Sopenharmony_ci    needs access to a shared resource created elsewhere can inherit it
28227db96d56Sopenharmony_ci    from an ancestor process.
28237db96d56Sopenharmony_ci
28247db96d56Sopenharmony_ciAvoid terminating processes
28257db96d56Sopenharmony_ci
28267db96d56Sopenharmony_ci    Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
28277db96d56Sopenharmony_ci    method to stop a process is liable to
28287db96d56Sopenharmony_ci    cause any shared resources (such as locks, semaphores, pipes and queues)
28297db96d56Sopenharmony_ci    currently being used by the process to become broken or unavailable to other
28307db96d56Sopenharmony_ci    processes.
28317db96d56Sopenharmony_ci
28327db96d56Sopenharmony_ci    Therefore it is probably best to only consider using
28337db96d56Sopenharmony_ci    :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
28347db96d56Sopenharmony_ci    which never use any shared resources.
28357db96d56Sopenharmony_ci
28367db96d56Sopenharmony_ciJoining processes that use queues
28377db96d56Sopenharmony_ci
28387db96d56Sopenharmony_ci    Bear in mind that a process that has put items in a queue will wait before
28397db96d56Sopenharmony_ci    terminating until all the buffered items are fed by the "feeder" thread to
28407db96d56Sopenharmony_ci    the underlying pipe.  (The child process can call the
28417db96d56Sopenharmony_ci    :meth:`Queue.cancel_join_thread <multiprocessing.Queue.cancel_join_thread>`
28427db96d56Sopenharmony_ci    method of the queue to avoid this behaviour.)
28437db96d56Sopenharmony_ci
28447db96d56Sopenharmony_ci    This means that whenever you use a queue you need to make sure that all
28457db96d56Sopenharmony_ci    items which have been put on the queue will eventually be removed before the
28467db96d56Sopenharmony_ci    process is joined.  Otherwise you cannot be sure that processes which have
28477db96d56Sopenharmony_ci    put items on the queue will terminate.  Remember also that non-daemonic
28487db96d56Sopenharmony_ci    processes will be joined automatically.
28497db96d56Sopenharmony_ci
28507db96d56Sopenharmony_ci    An example which will deadlock is the following::
28517db96d56Sopenharmony_ci
28527db96d56Sopenharmony_ci        from multiprocessing import Process, Queue
28537db96d56Sopenharmony_ci
28547db96d56Sopenharmony_ci        def f(q):
28557db96d56Sopenharmony_ci            q.put('X' * 1000000)
28567db96d56Sopenharmony_ci
28577db96d56Sopenharmony_ci        if __name__ == '__main__':
28587db96d56Sopenharmony_ci            queue = Queue()
28597db96d56Sopenharmony_ci            p = Process(target=f, args=(queue,))
28607db96d56Sopenharmony_ci            p.start()
28617db96d56Sopenharmony_ci            p.join()                    # this deadlocks
28627db96d56Sopenharmony_ci            obj = queue.get()
28637db96d56Sopenharmony_ci
28647db96d56Sopenharmony_ci    A fix here would be to swap the last two lines (or simply remove the
28657db96d56Sopenharmony_ci    ``p.join()`` line).
28667db96d56Sopenharmony_ci
28677db96d56Sopenharmony_ciExplicitly pass resources to child processes
28687db96d56Sopenharmony_ci
28697db96d56Sopenharmony_ci    On Unix using the *fork* start method, a child process can make
28707db96d56Sopenharmony_ci    use of a shared resource created in a parent process using a
28717db96d56Sopenharmony_ci    global resource.  However, it is better to pass the object as an
28727db96d56Sopenharmony_ci    argument to the constructor for the child process.
28737db96d56Sopenharmony_ci
28747db96d56Sopenharmony_ci    Apart from making the code (potentially) compatible with Windows
28757db96d56Sopenharmony_ci    and the other start methods this also ensures that as long as the
28767db96d56Sopenharmony_ci    child process is still alive the object will not be garbage
28777db96d56Sopenharmony_ci    collected in the parent process.  This might be important if some
28787db96d56Sopenharmony_ci    resource is freed when the object is garbage collected in the
28797db96d56Sopenharmony_ci    parent process.
28807db96d56Sopenharmony_ci
28817db96d56Sopenharmony_ci    So for instance ::
28827db96d56Sopenharmony_ci
28837db96d56Sopenharmony_ci        from multiprocessing import Process, Lock
28847db96d56Sopenharmony_ci
28857db96d56Sopenharmony_ci        def f():
28867db96d56Sopenharmony_ci            ... do something using "lock" ...
28877db96d56Sopenharmony_ci
28887db96d56Sopenharmony_ci        if __name__ == '__main__':
28897db96d56Sopenharmony_ci            lock = Lock()
28907db96d56Sopenharmony_ci            for i in range(10):
28917db96d56Sopenharmony_ci                Process(target=f).start()
28927db96d56Sopenharmony_ci
28937db96d56Sopenharmony_ci    should be rewritten as ::
28947db96d56Sopenharmony_ci
28957db96d56Sopenharmony_ci        from multiprocessing import Process, Lock
28967db96d56Sopenharmony_ci
28977db96d56Sopenharmony_ci        def f(l):
28987db96d56Sopenharmony_ci            ... do something using "l" ...
28997db96d56Sopenharmony_ci
29007db96d56Sopenharmony_ci        if __name__ == '__main__':
29017db96d56Sopenharmony_ci            lock = Lock()
29027db96d56Sopenharmony_ci            for i in range(10):
29037db96d56Sopenharmony_ci                Process(target=f, args=(lock,)).start()
29047db96d56Sopenharmony_ci
29057db96d56Sopenharmony_ciBeware of replacing :data:`sys.stdin` with a "file like object"
29067db96d56Sopenharmony_ci
29077db96d56Sopenharmony_ci    :mod:`multiprocessing` originally unconditionally called::
29087db96d56Sopenharmony_ci
29097db96d56Sopenharmony_ci        os.close(sys.stdin.fileno())
29107db96d56Sopenharmony_ci
29117db96d56Sopenharmony_ci    in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
29127db96d56Sopenharmony_ci    in issues with processes-in-processes. This has been changed to::
29137db96d56Sopenharmony_ci
29147db96d56Sopenharmony_ci        sys.stdin.close()
29157db96d56Sopenharmony_ci        sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)
29167db96d56Sopenharmony_ci
29177db96d56Sopenharmony_ci    Which solves the fundamental issue of processes colliding with each other
29187db96d56Sopenharmony_ci    resulting in a bad file descriptor error, but introduces a potential danger
29197db96d56Sopenharmony_ci    to applications which replace :func:`sys.stdin` with a "file-like object"
29207db96d56Sopenharmony_ci    with output buffering.  This danger is that if multiple processes call
29217db96d56Sopenharmony_ci    :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
29227db96d56Sopenharmony_ci    data being flushed to the object multiple times, resulting in corruption.
29237db96d56Sopenharmony_ci
29247db96d56Sopenharmony_ci    If you write a file-like object and implement your own caching, you can
29257db96d56Sopenharmony_ci    make it fork-safe by storing the pid whenever you append to the cache,
29267db96d56Sopenharmony_ci    and discarding the cache when the pid changes. For example::
29277db96d56Sopenharmony_ci
29287db96d56Sopenharmony_ci       @property
29297db96d56Sopenharmony_ci       def cache(self):
29307db96d56Sopenharmony_ci           pid = os.getpid()
29317db96d56Sopenharmony_ci           if pid != self._pid:
29327db96d56Sopenharmony_ci               self._pid = pid
29337db96d56Sopenharmony_ci               self._cache = []
29347db96d56Sopenharmony_ci           return self._cache
29357db96d56Sopenharmony_ci
29367db96d56Sopenharmony_ci    For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
29377db96d56Sopenharmony_ci
29387db96d56Sopenharmony_ciThe *spawn* and *forkserver* start methods
29397db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29407db96d56Sopenharmony_ci
29417db96d56Sopenharmony_ciThere are a few extra restriction which don't apply to the *fork*
29427db96d56Sopenharmony_cistart method.
29437db96d56Sopenharmony_ci
29447db96d56Sopenharmony_ciMore picklability
29457db96d56Sopenharmony_ci
29467db96d56Sopenharmony_ci    Ensure that all arguments to :meth:`Process.__init__` are picklable.
29477db96d56Sopenharmony_ci    Also, if you subclass :class:`~multiprocessing.Process` then make sure that
29487db96d56Sopenharmony_ci    instances will be picklable when the :meth:`Process.start
29497db96d56Sopenharmony_ci    <multiprocessing.Process.start>` method is called.
29507db96d56Sopenharmony_ci
29517db96d56Sopenharmony_ciGlobal variables
29527db96d56Sopenharmony_ci
29537db96d56Sopenharmony_ci    Bear in mind that if code run in a child process tries to access a global
29547db96d56Sopenharmony_ci    variable, then the value it sees (if any) may not be the same as the value
29557db96d56Sopenharmony_ci    in the parent process at the time that :meth:`Process.start
29567db96d56Sopenharmony_ci    <multiprocessing.Process.start>` was called.
29577db96d56Sopenharmony_ci
29587db96d56Sopenharmony_ci    However, global variables which are just module level constants cause no
29597db96d56Sopenharmony_ci    problems.
29607db96d56Sopenharmony_ci
29617db96d56Sopenharmony_ci.. _multiprocessing-safe-main-import:
29627db96d56Sopenharmony_ci
29637db96d56Sopenharmony_ciSafe importing of main module
29647db96d56Sopenharmony_ci
29657db96d56Sopenharmony_ci    Make sure that the main module can be safely imported by a new Python
29667db96d56Sopenharmony_ci    interpreter without causing unintended side effects (such a starting a new
29677db96d56Sopenharmony_ci    process).
29687db96d56Sopenharmony_ci
29697db96d56Sopenharmony_ci    For example, using the *spawn* or *forkserver* start method
29707db96d56Sopenharmony_ci    running the following module would fail with a
29717db96d56Sopenharmony_ci    :exc:`RuntimeError`::
29727db96d56Sopenharmony_ci
29737db96d56Sopenharmony_ci        from multiprocessing import Process
29747db96d56Sopenharmony_ci
29757db96d56Sopenharmony_ci        def foo():
29767db96d56Sopenharmony_ci            print('hello')
29777db96d56Sopenharmony_ci
29787db96d56Sopenharmony_ci        p = Process(target=foo)
29797db96d56Sopenharmony_ci        p.start()
29807db96d56Sopenharmony_ci
29817db96d56Sopenharmony_ci    Instead one should protect the "entry point" of the program by using ``if
29827db96d56Sopenharmony_ci    __name__ == '__main__':`` as follows::
29837db96d56Sopenharmony_ci
29847db96d56Sopenharmony_ci       from multiprocessing import Process, freeze_support, set_start_method
29857db96d56Sopenharmony_ci
29867db96d56Sopenharmony_ci       def foo():
29877db96d56Sopenharmony_ci           print('hello')
29887db96d56Sopenharmony_ci
29897db96d56Sopenharmony_ci       if __name__ == '__main__':
29907db96d56Sopenharmony_ci           freeze_support()
29917db96d56Sopenharmony_ci           set_start_method('spawn')
29927db96d56Sopenharmony_ci           p = Process(target=foo)
29937db96d56Sopenharmony_ci           p.start()
29947db96d56Sopenharmony_ci
29957db96d56Sopenharmony_ci    (The ``freeze_support()`` line can be omitted if the program will be run
29967db96d56Sopenharmony_ci    normally instead of frozen.)
29977db96d56Sopenharmony_ci
29987db96d56Sopenharmony_ci    This allows the newly spawned Python interpreter to safely import the module
29997db96d56Sopenharmony_ci    and then run the module's ``foo()`` function.
30007db96d56Sopenharmony_ci
30017db96d56Sopenharmony_ci    Similar restrictions apply if a pool or manager is created in the main
30027db96d56Sopenharmony_ci    module.
30037db96d56Sopenharmony_ci
30047db96d56Sopenharmony_ci
30057db96d56Sopenharmony_ci.. _multiprocessing-examples:
30067db96d56Sopenharmony_ci
30077db96d56Sopenharmony_ciExamples
30087db96d56Sopenharmony_ci--------
30097db96d56Sopenharmony_ci
30107db96d56Sopenharmony_ciDemonstration of how to create and use customized managers and proxies:
30117db96d56Sopenharmony_ci
30127db96d56Sopenharmony_ci.. literalinclude:: ../includes/mp_newtype.py
30137db96d56Sopenharmony_ci   :language: python3
30147db96d56Sopenharmony_ci
30157db96d56Sopenharmony_ci
30167db96d56Sopenharmony_ciUsing :class:`~multiprocessing.pool.Pool`:
30177db96d56Sopenharmony_ci
30187db96d56Sopenharmony_ci.. literalinclude:: ../includes/mp_pool.py
30197db96d56Sopenharmony_ci   :language: python3
30207db96d56Sopenharmony_ci
30217db96d56Sopenharmony_ci
30227db96d56Sopenharmony_ciAn example showing how to use queues to feed tasks to a collection of worker
30237db96d56Sopenharmony_ciprocesses and collect the results:
30247db96d56Sopenharmony_ci
30257db96d56Sopenharmony_ci.. literalinclude:: ../includes/mp_workers.py
3026