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