Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 1 | :mod:`multiprocessing` --- Process-based "threading" interface |
| 2 | ============================================================== |
| 3 | |
| 4 | .. module:: multiprocessing |
| 5 | :synopsis: Process-based "threading" interface. |
| 6 | |
| 7 | .. versionadded:: 2.6 |
| 8 | |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 9 | Introduction |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 10 | ---------------------- |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 11 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 12 | :mod:`multiprocessing` is a package that supports spawning processes |
| 13 | using an API similar to the :mod:`threading` module. The |
| 14 | :mod:`multiprocessing` package offers both local and remote |
| 15 | concurrency, effectively side-stepping the :term:`Global Interpreter |
| 16 | Lock` by using subprocesses instead of threads. Due to this, the |
| 17 | :mod:`multiprocessing` module allows the programmer to fully leverage |
| 18 | multiple processors on a given machine. It runs on both Unix and |
| 19 | Windows. |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 20 | |
| 21 | The :class:`Process` class |
| 22 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 23 | |
| 24 | In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process` |
| 25 | object and then calling its :meth:`Process.start` method. :class:`Process` |
| 26 | follows the API of :class:`threading.Thread`. A trivial example of a |
| 27 | multiprocess program is :: |
| 28 | |
| 29 | from multiprocessing import Process |
| 30 | |
| 31 | def f(name): |
| 32 | print 'hello', name |
| 33 | |
| 34 | if __name__ == '__main__': |
| 35 | p = Process(target=f, args=('bob',)) |
| 36 | p.start() |
| 37 | p.join() |
| 38 | |
| 39 | Here the function ``f`` is run in a child process. |
| 40 | |
| 41 | For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is |
| 42 | necessary, see :ref:`multiprocessing-programming`. |
| 43 | |
| 44 | |
| 45 | |
| 46 | Exchanging objects between processes |
| 47 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 48 | |
| 49 | :mod:`multiprocessing` supports two types of communication channel between |
| 50 | processes: |
| 51 | |
| 52 | **Queues** |
| 53 | |
| 54 | The :class:`Queue` class is a near clone of :class:`Queue.Queue`. For |
| 55 | example:: |
| 56 | |
| 57 | from multiprocessing import Process, Queue |
| 58 | |
| 59 | def f(q): |
| 60 | q.put([42, None, 'hello']) |
| 61 | |
| 62 | if __name__ == '__main__': |
| 63 | q = Queue() |
| 64 | p = Process(target=f, args=(q,)) |
| 65 | p.start() |
| 66 | print q.get() # prints "[42, None, 'hello']" |
| 67 | p.join() |
| 68 | |
| 69 | Queues are thread and process safe. |
| 70 | |
| 71 | **Pipes** |
| 72 | |
| 73 | The :func:`Pipe` function returns a pair of connection objects connected by a |
| 74 | pipe which by default is duplex (two-way). For example:: |
| 75 | |
| 76 | from multiprocessing import Process, Pipe |
| 77 | |
| 78 | def f(conn): |
| 79 | conn.send([42, None, 'hello']) |
| 80 | conn.close() |
| 81 | |
| 82 | if __name__ == '__main__': |
| 83 | parent_conn, child_conn = Pipe() |
| 84 | p = Process(target=f, args=(child_conn,)) |
| 85 | p.start() |
| 86 | print parent_conn.recv() # prints "[42, None, 'hello']" |
| 87 | p.join() |
| 88 | |
| 89 | The two connection objects returned by :func:`Pipe` represent the two ends of |
| 90 | the pipe. Each connection object has :meth:`send` and :meth:`recv` methods |
| 91 | (among others). Note that data in a pipe may become corrupted if two |
| 92 | processes (or threads) try to read from or write to the *same* end of the |
| 93 | pipe at the same time. Of course there is no risk of corruption from |
| 94 | processes using different ends of the pipe at the same time. |
| 95 | |
| 96 | |
| 97 | Synchronization between processes |
| 98 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 99 | |
| 100 | :mod:`multiprocessing` contains equivalents of all the synchronization |
| 101 | primitives from :mod:`threading`. For instance one can use a lock to ensure |
| 102 | that only one process prints to standard output at a time:: |
| 103 | |
| 104 | from multiprocessing import Process, Lock |
| 105 | |
| 106 | def f(l, i): |
| 107 | l.acquire() |
| 108 | print 'hello world', i |
| 109 | l.release() |
| 110 | |
| 111 | if __name__ == '__main__': |
| 112 | lock = Lock() |
| 113 | |
| 114 | for num in range(10): |
| 115 | Process(target=f, args=(lock, num)).start() |
| 116 | |
| 117 | Without using the lock output from the different processes is liable to get all |
| 118 | mixed up. |
| 119 | |
| 120 | |
| 121 | Sharing state between processes |
| 122 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 123 | |
| 124 | As mentioned above, when doing concurrent programming it is usually best to |
| 125 | avoid using shared state as far as possible. This is particularly true when |
| 126 | using multiple processes. |
| 127 | |
| 128 | However, if you really do need to use some shared data then |
| 129 | :mod:`multiprocessing` provides a couple of ways of doing so. |
| 130 | |
| 131 | **Shared memory** |
| 132 | |
| 133 | Data can be stored in a shared memory map using :class:`Value` or |
| 134 | :class:`Array`. For example, the following code :: |
| 135 | |
| 136 | from multiprocessing import Process, Value, Array |
| 137 | |
| 138 | def f(n, a): |
| 139 | n.value = 3.1415927 |
| 140 | for i in range(len(a)): |
| 141 | a[i] = -a[i] |
| 142 | |
| 143 | if __name__ == '__main__': |
| 144 | num = Value('d', 0.0) |
| 145 | arr = Array('i', range(10)) |
| 146 | |
| 147 | p = Process(target=f, args=(num, arr)) |
| 148 | p.start() |
| 149 | p.join() |
| 150 | |
| 151 | print num.value |
| 152 | print arr[:] |
| 153 | |
| 154 | will print :: |
| 155 | |
| 156 | 3.1415927 |
| 157 | [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] |
| 158 | |
| 159 | The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are |
| 160 | typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a |
| 161 | double precision float and ``'i'`` inidicates a signed integer. These shared |
| 162 | objects will be process and thread safe. |
| 163 | |
| 164 | For more flexibility in using shared memory one can use the |
| 165 | :mod:`multiprocessing.sharedctypes` module which supports the creation of |
| 166 | arbitrary ctypes objects allocated from shared memory. |
| 167 | |
| 168 | **Server process** |
| 169 | |
| 170 | A manager object returned by :func:`Manager` controls a server process which |
| 171 | holds python objects and allows other processes to manipulate them using |
| 172 | proxies. |
| 173 | |
| 174 | A manager returned by :func:`Manager` will support types :class:`list`, |
| 175 | :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`, |
| 176 | :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`, |
| 177 | :class:`Event`, :class:`Queue`, :class:`Value` and :class:`Array`. For |
| 178 | example, :: |
| 179 | |
| 180 | from multiprocessing import Process, Manager |
| 181 | |
| 182 | def f(d, l): |
| 183 | d[1] = '1' |
| 184 | d['2'] = 2 |
| 185 | d[0.25] = None |
| 186 | l.reverse() |
| 187 | |
| 188 | if __name__ == '__main__': |
| 189 | manager = Manager() |
| 190 | |
| 191 | d = manager.dict() |
| 192 | l = manager.list(range(10)) |
| 193 | |
| 194 | p = Process(target=f, args=(d, l)) |
| 195 | p.start() |
| 196 | p.join() |
| 197 | |
| 198 | print d |
| 199 | print l |
| 200 | |
| 201 | will print :: |
| 202 | |
| 203 | {0.25: None, 1: '1', '2': 2} |
| 204 | [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] |
| 205 | |
| 206 | Server process managers are more flexible than using shared memory objects |
| 207 | because they can be made to support arbitrary object types. Also, a single |
| 208 | manager can be shared by processes on different computers over a network. |
| 209 | They are, however, slower than using shared memory. |
| 210 | |
| 211 | |
| 212 | Using a pool of workers |
| 213 | ~~~~~~~~~~~~~~~~~~~~~~~ |
| 214 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 215 | The :class:`multiprocessing.pool.Pool()` class represents a pool of worker |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 216 | processes. It has methods which allows tasks to be offloaded to the worker |
| 217 | processes in a few different ways. |
| 218 | |
| 219 | For example:: |
| 220 | |
| 221 | from multiprocessing import Pool |
| 222 | |
| 223 | def f(x): |
| 224 | return x*x |
| 225 | |
| 226 | if __name__ == '__main__': |
| 227 | pool = Pool(processes=4) # start 4 worker processes |
| 228 | result = pool.applyAsync(f, [10]) # evaluate "f(10)" asynchronously |
| 229 | print result.get(timeout=1) # prints "100" unless your computer is *very* slow |
| 230 | print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" |
| 231 | |
| 232 | |
| 233 | Reference |
| 234 | --------- |
| 235 | |
| 236 | The :mod:`multiprocessing` package mostly replicates the API of the |
| 237 | :mod:`threading` module. |
| 238 | |
| 239 | |
| 240 | :class:`Process` and exceptions |
| 241 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 242 | |
| 243 | .. class:: Process([group[, target[, name[, args[, kwargs]]]]]) |
| 244 | |
| 245 | Process objects represent activity that is run in a separate process. The |
| 246 | :class:`Process` class has equivalents of all the methods of |
| 247 | :class:`threading.Thread`. |
| 248 | |
| 249 | The constructor should always be called with keyword arguments. *group* |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 250 | should always be ``None``; it exists solely for compatibility with |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 251 | :class:`threading.Thread`. *target* is the callable object to be invoked by |
| 252 | the :meth:`run()` method. It defaults to None, meaning nothing is |
| 253 | called. *name* is the process name. By default, a unique name is constructed |
| 254 | of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\ |
| 255 | :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length |
| 256 | is determined by the *generation* of the process. *args* is the argument |
| 257 | tuple for the target invocation. *kwargs* is a dictionary of keyword |
| 258 | arguments for the target invocation. By default, no arguments are passed to |
| 259 | *target*. |
| 260 | |
| 261 | If a subclass overrides the constructor, it must make sure it invokes the |
| 262 | base class constructor (:meth:`Process.__init__`) before doing anything else |
| 263 | to the process. |
| 264 | |
| 265 | .. method:: run() |
| 266 | |
| 267 | Method representing the process's activity. |
| 268 | |
| 269 | You may override this method in a subclass. The standard :meth:`run` |
| 270 | method invokes the callable object passed to the object's constructor as |
| 271 | the target argument, if any, with sequential and keyword arguments taken |
| 272 | from the *args* and *kwargs* arguments, respectively. |
| 273 | |
| 274 | .. method:: start() |
| 275 | |
| 276 | Start the process's activity. |
| 277 | |
| 278 | This must be called at most once per process object. It arranges for the |
| 279 | object's :meth:`run` method to be invoked in a separate process. |
| 280 | |
| 281 | .. method:: join([timeout]) |
| 282 | |
| 283 | Block the calling thread until the process whose :meth:`join` method is |
| 284 | called terminates or until the optional timeout occurs. |
| 285 | |
| 286 | If *timeout* is ``None`` then there is no timeout. |
| 287 | |
| 288 | A process can be joined many times. |
| 289 | |
| 290 | A process cannot join itself because this would cause a deadlock. It is |
| 291 | an error to attempt to join a process before it has been started. |
| 292 | |
| 293 | .. method:: get_name() |
| 294 | |
| 295 | Return the process's name. |
| 296 | |
| 297 | .. method:: set_name(name) |
| 298 | |
| 299 | Set the process's name. |
| 300 | |
| 301 | The name is a string used for identification purposes only. It has no |
| 302 | semantics. Multiple processes may be given the same name. The initial |
| 303 | name is set by the constructor. |
| 304 | |
| 305 | .. method:: is_alive() |
| 306 | |
| 307 | Return whether the process is alive. |
| 308 | |
| 309 | Roughly, a process object is alive from the moment the :meth:`start` |
| 310 | method returns until the child process terminates. |
| 311 | |
| 312 | .. method:: is_daemon() |
| 313 | |
| 314 | Return the process's daemon flag. |
| 315 | |
| 316 | .. method:: set_daemon(daemonic) |
| 317 | |
| 318 | Set the process's daemon flag to the Boolean value *daemonic*. This must |
| 319 | be called before :meth:`start` is called. |
| 320 | |
| 321 | The initial value is inherited from the creating process. |
| 322 | |
| 323 | When a process exits, it attempts to terminate all of its daemonic child |
| 324 | processes. |
| 325 | |
| 326 | Note that a daemonic process is not allowed to create child processes. |
| 327 | Otherwise a daemonic process would leave its children orphaned if it gets |
| 328 | terminated when its parent process exits. |
| 329 | |
| 330 | In addition process objects also support the following methods: |
| 331 | |
| 332 | .. method:: get_pid() |
| 333 | |
| 334 | Return the process ID. Before the process is spawned, this will be |
| 335 | ``None``. |
| 336 | |
| 337 | .. method:: get_exit_code() |
| 338 | |
| 339 | Return the child's exit code. This will be ``None`` if the process has |
| 340 | not yet terminated. A negative value *-N* indicates that the child was |
| 341 | terminated by signal *N*. |
| 342 | |
| 343 | .. method:: get_auth_key() |
| 344 | |
| 345 | Return the process's authentication key (a byte string). |
| 346 | |
| 347 | When :mod:`multiprocessing` is initialized the main process is assigned a |
| 348 | random string using :func:`os.random`. |
| 349 | |
| 350 | When a :class:`Process` object is created, it will inherit the |
| 351 | authentication key of its parent process, although this may be changed |
| 352 | using :meth:`set_auth_key` below. |
| 353 | |
| 354 | See :ref:`multiprocessing-auth-keys`. |
| 355 | |
| 356 | .. method:: set_auth_key(authkey) |
| 357 | |
| 358 | Set the process's authentication key which must be a byte string. |
| 359 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 360 | .. method:: terminate() |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 361 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 362 | Terminate the process. On Unix this is done using the ``SIGTERM`` signal; |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 363 | on Windows ``TerminateProcess()`` is used. Note that exit handlers and |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 364 | finally clauses, etc., will not be executed. |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 365 | |
| 366 | Note that descendant processes of the process will *not* be terminated -- |
| 367 | they will simply become orphaned. |
| 368 | |
| 369 | .. warning:: |
| 370 | |
| 371 | If this method is used when the associated process is using a pipe or |
| 372 | queue then the pipe or queue is liable to become corrupted and may |
| 373 | become unusable by other process. Similarly, if the process has |
| 374 | acquired a lock or semaphore etc. then terminating it is liable to |
| 375 | cause other processes to deadlock. |
| 376 | |
| 377 | Note that the :meth:`start`, :meth:`join`, :meth:`is_alive` and |
| 378 | :meth:`get_exit_code` methods should only be called by the process that |
| 379 | created the process object. |
| 380 | |
| 381 | Example usage of some of the methods of :class:`Process`:: |
| 382 | |
| 383 | >>> import processing, time, signal |
| 384 | >>> p = processing.Process(target=time.sleep, args=(1000,)) |
| 385 | >>> print p, p.is_alive() |
| 386 | <Process(Process-1, initial)> False |
| 387 | >>> p.start() |
| 388 | >>> print p, p.is_alive() |
| 389 | <Process(Process-1, started)> True |
| 390 | >>> p.terminate() |
| 391 | >>> print p, p.is_alive() |
| 392 | <Process(Process-1, stopped[SIGTERM])> False |
| 393 | >>> p.get_exit_code() == -signal.SIGTERM |
| 394 | True |
| 395 | |
| 396 | |
| 397 | .. exception:: BufferTooShort |
| 398 | |
| 399 | Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied |
| 400 | buffer object is too small for the message read. |
| 401 | |
| 402 | If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give |
| 403 | the message as a byte string. |
| 404 | |
| 405 | |
| 406 | Pipes and Queues |
| 407 | ~~~~~~~~~~~~~~~~ |
| 408 | |
| 409 | When using multiple processes, one generally uses message passing for |
| 410 | communication between processes and avoids having to use any synchronization |
| 411 | primitives like locks. |
| 412 | |
| 413 | For passing messages one can use :func:`Pipe` (for a connection between two |
| 414 | processes) or a queue (which allows multiple producers and consumers). |
| 415 | |
| 416 | The :class:`Queue` and :class:`JoinableQueue` types are multi-producer, |
| 417 | multi-consumer FIFO queues modelled on the :class:`Queue.Queue` class in the |
| 418 | standard library. They differ in that :class:`Queue` lacks the |
| 419 | :meth:`task_done` and :meth:`join` methods introduced into Python 2.5's |
| 420 | :class:`Queue.Queue` class. |
| 421 | |
| 422 | If you use :class:`JoinableQueue` then you **must** call |
| 423 | :meth:`JoinableQueue.task_done` for each task removed from the queue or else the |
| 424 | semaphore used to count the number of unfinished tasks may eventually overflow |
| 425 | raising an exception. |
| 426 | |
| 427 | .. note:: |
| 428 | |
| 429 | :mod:`multiprocessing` uses the usual :exc:`Queue.Empty` and |
| 430 | :exc:`Queue.Full` exceptions to signal a timeout. They are not available in |
| 431 | the :mod:`multiprocessing` namespace so you need to import them from |
| 432 | :mod:`Queue`. |
| 433 | |
| 434 | |
| 435 | .. warning:: |
| 436 | |
| 437 | If a process is killed using :meth:`Process.terminate` or :func:`os.kill` |
| 438 | while it is trying to use a :class:`Queue`, then the data in the queue is |
| 439 | likely to become corrupted. This may cause any other processes to get an |
| 440 | exception when it tries to use the queue later on. |
| 441 | |
| 442 | .. warning:: |
| 443 | |
| 444 | As mentioned above, if a child process has put items on a queue (and it has |
| 445 | not used :meth:`JoinableQueue.cancel_join_thread`), then that process will |
| 446 | not terminate until all buffered items have been flushed to the pipe. |
| 447 | |
| 448 | This means that if you try joining that process you may get a deadlock unless |
| 449 | you are sure that all items which have been put on the queue have been |
| 450 | consumed. Similarly, if the child process is non-daemonic then the parent |
| 451 | process may hang on exit when it tries to join all it non-daemonic children. |
| 452 | |
| 453 | Note that a queue created using a manager does not have this issue. See |
| 454 | :ref:`multiprocessing-programming`. |
| 455 | |
| 456 | Note that one can also create a shared queue by using a manager object -- see |
| 457 | :ref:`multiprocessing-managers`. |
| 458 | |
| 459 | For an example of the usage of queues for interprocess communication see |
| 460 | :ref:`multiprocessing-examples`. |
| 461 | |
| 462 | |
| 463 | .. function:: Pipe([duplex]) |
| 464 | |
| 465 | Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing |
| 466 | the ends of a pipe. |
| 467 | |
| 468 | If *duplex* is ``True`` (the default) then the pipe is bidirectional. If |
| 469 | *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be |
| 470 | used for receiving messages and ``conn2`` can only be used for sending |
| 471 | messages. |
| 472 | |
| 473 | |
| 474 | .. class:: Queue([maxsize]) |
| 475 | |
| 476 | Returns a process shared queue implemented using a pipe and a few |
| 477 | locks/semaphores. When a process first puts an item on the queue a feeder |
| 478 | thread is started which transfers objects from a buffer into the pipe. |
| 479 | |
| 480 | The usual :exc:`Queue.Empty` and :exc:`Queue.Full` exceptions from the |
| 481 | standard library's :mod:`Queue` module are raised to signal timeouts. |
| 482 | |
| 483 | :class:`Queue` implements all the methods of :class:`Queue.Queue` except for |
| 484 | :meth:`task_done` and :meth:`join`. |
| 485 | |
| 486 | .. method:: qsize() |
| 487 | |
| 488 | Return the approximate size of the queue. Because of |
| 489 | multithreading/multiprocessing semantics, this number is not reliable. |
| 490 | |
| 491 | Note that this may raise :exc:`NotImplementedError` on Unix platforms like |
| 492 | MacOS X where ``sem_getvalue()`` is not implemented. |
| 493 | |
| 494 | .. method:: empty() |
| 495 | |
| 496 | Return ``True`` if the queue is empty, ``False`` otherwise. Because of |
| 497 | multithreading/multiprocessing semantics, this is not reliable. |
| 498 | |
| 499 | .. method:: full() |
| 500 | |
| 501 | Return ``True`` if the queue is full, ``False`` otherwise. Because of |
| 502 | multithreading/multiprocessing semantics, this is not reliable. |
| 503 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 504 | .. method:: put(item[, block[, timeout]]) |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 505 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 506 | Put item into the queue. If the optional argument *block* is ``True`` |
| 507 | (the default) and *timeout* is ``None`` (the default), block if necessary until |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 508 | a free slot is available. If *timeout* is a positive number, it blocks at |
| 509 | most *timeout* seconds and raises the :exc:`Queue.Full` exception if no |
| 510 | free slot was available within that time. Otherwise (*block* is |
| 511 | ``False``), put an item on the queue if a free slot is immediately |
| 512 | available, else raise the :exc:`Queue.Full` exception (*timeout* is |
| 513 | ignored in that case). |
| 514 | |
| 515 | .. method:: put_nowait(item) |
| 516 | |
| 517 | Equivalent to ``put(item, False)``. |
| 518 | |
| 519 | .. method:: get([block[, timeout]]) |
| 520 | |
| 521 | Remove and return an item from the queue. If optional args *block* is |
| 522 | ``True`` (the default) and *timeout* is ``None`` (the default), block if |
| 523 | necessary until an item is available. If *timeout* is a positive number, |
| 524 | it blocks at most *timeout* seconds and raises the :exc:`Queue.Empty` |
| 525 | exception if no item was available within that time. Otherwise (block is |
| 526 | ``False``), return an item if one is immediately available, else raise the |
| 527 | :exc:`Queue.Empty` exception (*timeout* is ignored in that case). |
| 528 | |
| 529 | .. method:: get_nowait() |
| 530 | get_no_wait() |
| 531 | |
| 532 | Equivalent to ``get(False)``. |
| 533 | |
| 534 | :class:`multiprocessing.Queue` has a few additional methods not found in |
| 535 | :class:`Queue.Queue` which are usually unnecessary: |
| 536 | |
| 537 | .. method:: close() |
| 538 | |
| 539 | Indicate that no more data will be put on this queue by the current |
| 540 | process. The background thread will quit once it has flushed all buffered |
| 541 | data to the pipe. This is called automatically when the queue is garbage |
| 542 | collected. |
| 543 | |
| 544 | .. method:: join_thread() |
| 545 | |
| 546 | Join the background thread. This can only be used after :meth:`close` has |
| 547 | been called. It blocks until the background thread exits, ensuring that |
| 548 | all data in the buffer has been flushed to the pipe. |
| 549 | |
| 550 | By default if a process is not the creator of the queue then on exit it |
| 551 | will attempt to join the queue's background thread. The process can call |
| 552 | :meth:`cancel_join_thread()` to make :meth:`join_thread()` do nothing. |
| 553 | |
| 554 | .. method:: cancel_join_thread() |
| 555 | |
| 556 | Prevent :meth:`join_thread` from blocking. In particular, this prevents |
| 557 | the background thread from being joined automatically when the process |
| 558 | exits -- see :meth:`join_thread()`. |
| 559 | |
| 560 | |
| 561 | .. class:: JoinableQueue([maxsize]) |
| 562 | |
| 563 | :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which |
| 564 | additionally has :meth:`task_done` and :meth:`join` methods. |
| 565 | |
| 566 | .. method:: task_done() |
| 567 | |
| 568 | Indicate that a formerly enqueued task is complete. Used by queue consumer |
| 569 | threads. For each :meth:`get` used to fetch a task, a subsequent call to |
| 570 | :meth:`task_done` tells the queue that the processing on the task is |
| 571 | complete. |
| 572 | |
| 573 | If a :meth:`join` is currently blocking, it will resume when all items |
| 574 | have been processed (meaning that a :meth:`task_done` call was received |
| 575 | for every item that had been :meth:`put` into the queue). |
| 576 | |
| 577 | Raises a :exc:`ValueError` if called more times than there were items |
| 578 | placed in the queue. |
| 579 | |
| 580 | |
| 581 | .. method:: join() |
| 582 | |
| 583 | Block until all items in the queue have been gotten and processed. |
| 584 | |
| 585 | The count of unfinished tasks goes up whenever an item is added to the |
| 586 | queue. The count goes down whenever a consumer thread calls |
| 587 | :meth:`task_done` to indicate that the item was retrieved and all work on |
| 588 | it is complete. When the count of unfinished tasks drops to zero, |
| 589 | :meth:`join` unblocks. |
| 590 | |
| 591 | |
| 592 | Miscellaneous |
| 593 | ~~~~~~~~~~~~~ |
| 594 | |
| 595 | .. function:: active_children() |
| 596 | |
| 597 | Return list of all live children of the current process. |
| 598 | |
| 599 | Calling this has the side affect of "joining" any processes which have |
| 600 | already finished. |
| 601 | |
| 602 | .. function:: cpu_count() |
| 603 | |
| 604 | Return the number of CPUs in the system. May raise |
| 605 | :exc:`NotImplementedError`. |
| 606 | |
| 607 | .. function:: current_process() |
| 608 | |
| 609 | Return the :class:`Process` object corresponding to the current process. |
| 610 | |
| 611 | An analogue of :func:`threading.current_thread`. |
| 612 | |
| 613 | .. function:: freeze_support() |
| 614 | |
| 615 | Add support for when a program which uses :mod:`multiprocessing` has been |
| 616 | frozen to produce a Windows executable. (Has been tested with **py2exe**, |
| 617 | **PyInstaller** and **cx_Freeze**.) |
| 618 | |
| 619 | One needs to call this function straight after the ``if __name__ == |
| 620 | '__main__'`` line of the main module. For example:: |
| 621 | |
| 622 | from multiprocessing import Process, freeze_support |
| 623 | |
| 624 | def f(): |
| 625 | print 'hello world!' |
| 626 | |
| 627 | if __name__ == '__main__': |
| 628 | freeze_support() |
| 629 | Process(target=f).start() |
| 630 | |
| 631 | If the :func:`freeze_support()` line is missed out then trying to run the |
| 632 | frozen executable will raise :exc:`RuntimeError`. |
| 633 | |
| 634 | If the module is being run normally by the Python interpreter then |
| 635 | :func:`freeze_support()` has no effect. |
| 636 | |
| 637 | .. function:: set_executable() |
| 638 | |
| 639 | Sets the path of the python interpreter to use when starting a child process. |
| 640 | (By default `sys.executable` is used). Embedders will probably need to do |
| 641 | some thing like :: |
| 642 | |
| 643 | setExecutable(os.path.join(sys.exec_prefix, 'pythonw.exe')) |
| 644 | |
| 645 | before they can create child processes. (Windows only) |
| 646 | |
| 647 | |
| 648 | .. note:: |
| 649 | |
| 650 | :mod:`multiprocessing` contains no analogues of |
| 651 | :func:`threading.active_count`, :func:`threading.enumerate`, |
| 652 | :func:`threading.settrace`, :func:`threading.setprofile`, |
| 653 | :class:`threading.Timer`, or :class:`threading.local`. |
| 654 | |
| 655 | |
| 656 | Connection Objects |
| 657 | ~~~~~~~~~~~~~~~~~~ |
| 658 | |
| 659 | Connection objects allow the sending and receiving of picklable objects or |
| 660 | strings. They can be thought of as message oriented connected sockets. |
| 661 | |
| 662 | Connection objects usually created using :func:`Pipe()` -- see also |
| 663 | :ref:`multiprocessing-listeners-clients`. |
| 664 | |
| 665 | .. class:: Connection |
| 666 | |
| 667 | .. method:: send(obj) |
| 668 | |
| 669 | Send an object to the other end of the connection which should be read |
| 670 | using :meth:`recv`. |
| 671 | |
| 672 | The object must be picklable. |
| 673 | |
| 674 | .. method:: recv() |
| 675 | |
| 676 | Return an object sent from the other end of the connection using |
| 677 | :meth:`send`. Raises :exc:`EOFError` if there is nothing left to receive |
| 678 | and the other end was closed. |
| 679 | |
| 680 | .. method:: fileno() |
| 681 | |
| 682 | Returns the file descriptor or handle used by the connection. |
| 683 | |
| 684 | .. method:: close() |
| 685 | |
| 686 | Close the connection. |
| 687 | |
| 688 | This is called automatically when the connection is garbage collected. |
| 689 | |
| 690 | .. method:: poll([timeout]) |
| 691 | |
| 692 | Return whether there is any data available to be read. |
| 693 | |
| 694 | If *timeout* is not specified then it will return immediately. If |
| 695 | *timeout* is a number then this specifies the maximum time in seconds to |
| 696 | block. If *timeout* is ``None`` then an infinite timeout is used. |
| 697 | |
| 698 | .. method:: send_bytes(buffer[, offset[, size]]) |
| 699 | |
| 700 | Send byte data from an object supporting the buffer interface as a |
| 701 | complete message. |
| 702 | |
| 703 | If *offset* is given then data is read from that position in *buffer*. If |
| 704 | *size* is given then that many bytes will be read from buffer. |
| 705 | |
| 706 | .. method:: recv_bytes([maxlength]) |
| 707 | |
| 708 | Return a complete message of byte data sent from the other end of the |
| 709 | connection as a string. Raises :exc:`EOFError` if there is nothing left |
| 710 | to receive and the other end has closed. |
| 711 | |
| 712 | If *maxlength* is specified and the message is longer than *maxlength* |
| 713 | then :exc:`IOError` is raised and the connection will no longer be |
| 714 | readable. |
| 715 | |
| 716 | .. method:: recv_bytes_into(buffer[, offset]) |
| 717 | |
| 718 | Read into *buffer* a complete message of byte data sent from the other end |
| 719 | of the connection and return the number of bytes in the message. Raises |
| 720 | :exc:`EOFError` if there is nothing left to receive and the other end was |
| 721 | closed. |
| 722 | |
| 723 | *buffer* must be an object satisfying the writable buffer interface. If |
| 724 | *offset* is given then the message will be written into the buffer from |
| 725 | *that position. Offset must be a non-negative integer less than the |
| 726 | *length of *buffer* (in bytes). |
| 727 | |
| 728 | If the buffer is too short then a :exc:`BufferTooShort` exception is |
| 729 | raised and the complete message is available as ``e.args[0]`` where ``e`` |
| 730 | is the exception instance. |
| 731 | |
| 732 | |
| 733 | For example: |
| 734 | |
| 735 | >>> from multiprocessing import Pipe |
| 736 | >>> a, b = Pipe() |
| 737 | >>> a.send([1, 'hello', None]) |
| 738 | >>> b.recv() |
| 739 | [1, 'hello', None] |
| 740 | >>> b.send_bytes('thank you') |
| 741 | >>> a.recv_bytes() |
| 742 | 'thank you' |
| 743 | >>> import array |
| 744 | >>> arr1 = array.array('i', range(5)) |
| 745 | >>> arr2 = array.array('i', [0] * 10) |
| 746 | >>> a.send_bytes(arr1) |
| 747 | >>> count = b.recv_bytes_into(arr2) |
| 748 | >>> assert count == len(arr1) * arr1.itemsize |
| 749 | >>> arr2 |
| 750 | array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0]) |
| 751 | |
| 752 | |
| 753 | .. warning:: |
| 754 | |
| 755 | The :meth:`Connection.recv` method automatically unpickles the data it |
| 756 | receives, which can be a security risk unless you can trust the process |
| 757 | which sent the message. |
| 758 | |
| 759 | Therefore, unless the connection object was produced using :func:`Pipe()` |
| 760 | you should only use the `recv()` and `send()` methods after performing some |
| 761 | sort of authentication. See :ref:`multiprocessing-auth-keys`. |
| 762 | |
| 763 | .. warning:: |
| 764 | |
| 765 | If a process is killed while it is trying to read or write to a pipe then |
| 766 | the data in the pipe is likely to become corrupted, because it may become |
| 767 | impossible to be sure where the message boundaries lie. |
| 768 | |
| 769 | |
| 770 | Synchronization primitives |
| 771 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 772 | |
| 773 | Generally synchronization primitives are not as necessary in a multiprocess |
| 774 | program as they are in a mulithreaded program. See the documentation for the |
| 775 | standard library's :mod:`threading` module. |
| 776 | |
| 777 | Note that one can also create synchronization primitives by using a manager |
| 778 | object -- see :ref:`multiprocessing-managers`. |
| 779 | |
| 780 | .. class:: BoundedSemaphore([value]) |
| 781 | |
| 782 | A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`. |
| 783 | |
| 784 | (On Mac OSX this is indistiguishable from :class:`Semaphore` because |
| 785 | ``sem_getvalue()`` is not implemented on that platform). |
| 786 | |
| 787 | .. class:: Condition([lock]) |
| 788 | |
| 789 | A condition variable: a clone of `threading.Condition`. |
| 790 | |
| 791 | If *lock* is specified then it should be a :class:`Lock` or :class:`RLock` |
| 792 | object from :mod:`multiprocessing`. |
| 793 | |
| 794 | .. class:: Event() |
| 795 | |
| 796 | A clone of :class:`threading.Event`. |
| 797 | |
| 798 | .. class:: Lock() |
| 799 | |
| 800 | A non-recursive lock object: a clone of :class:`threading.Lock`. |
| 801 | |
| 802 | .. class:: RLock() |
| 803 | |
| 804 | A recursive lock object: a clone of :class:`threading.RLock`. |
| 805 | |
| 806 | .. class:: Semaphore([value]) |
| 807 | |
| 808 | A bounded semaphore object: a clone of :class:`threading.Semaphore`. |
| 809 | |
| 810 | .. note:: |
| 811 | |
| 812 | The :meth:`acquire()` method of :class:`BoundedSemaphore`, :class:`Lock`, |
| 813 | :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported |
| 814 | by the equivalents in :mod:`threading`. The signature is |
| 815 | ``acquire(block=True, timeout=None)`` with keyword parameters being |
| 816 | acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it |
| 817 | specifies a timeout in seconds. If *block* is ``False`` then *timeout* is |
| 818 | ignored. |
| 819 | |
| 820 | .. note:: |
| 821 | |
| 822 | If the SIGINT signal generated by Ctrl-C arrives while the main thread is |
| 823 | blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`, |
| 824 | :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire` |
| 825 | or :meth:`Condition.wait` then the call will be immediately interrupted and |
| 826 | :exc:`KeyboardInterrupt` will be raised. |
| 827 | |
| 828 | This differs from the behaviour of :mod:`threading` where SIGINT will be |
| 829 | ignored while the equivalent blocking calls are in progress. |
| 830 | |
| 831 | |
| 832 | Shared :mod:`ctypes` Objects |
| 833 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 834 | |
| 835 | It is possible to create shared objects using shared memory which can be |
| 836 | inherited by child processes. |
| 837 | |
| 838 | .. function:: Value(typecode_or_type[, lock[, *args]]) |
| 839 | |
| 840 | Return a :mod:`ctypes` object allocated from shared memory. By default the |
| 841 | return value is actually a synchronized wrapper for the object. |
| 842 | |
| 843 | *typecode_or_type* determines the type of the returned object: it is either a |
| 844 | ctypes type or a one character typecode of the kind used by the :mod:`array` |
| 845 | module. *\*args* is passed on to the constructor for the type. |
| 846 | |
| 847 | If *lock* is ``True`` (the default) then a new lock object is created to |
| 848 | synchronize access to the value. If *lock* is a :class:`Lock` or |
| 849 | :class:`RLock` object then that will be used to synchronize access to the |
| 850 | value. If *lock* is ``False`` then access to the returned object will not be |
| 851 | automatically protected by a lock, so it will not necessarily be |
| 852 | "process-safe". |
| 853 | |
| 854 | Note that *lock* is a keyword-only argument. |
| 855 | |
| 856 | .. function:: Array(typecode_or_type, size_or_initializer, *, lock=True) |
| 857 | |
| 858 | Return a ctypes array allocated from shared memory. By default the return |
| 859 | value is actually a synchronized wrapper for the array. |
| 860 | |
| 861 | *typecode_or_type* determines the type of the elements of the returned array: |
| 862 | it is either a ctypes type or a one character typecode of the kind used by |
| 863 | the :mod:`array` module. If *size_or_initializer* is an integer, then it |
| 864 | determines the length of the array, and the array will be initially zeroed. |
| 865 | Otherwise, *size_or_initializer* is a sequence which is used to initialize |
| 866 | the array and whose length determines the length of the array. |
| 867 | |
| 868 | If *lock* is ``True`` (the default) then a new lock object is created to |
| 869 | synchronize access to the value. If *lock* is a :class:`Lock` or |
| 870 | :class:`RLock` object then that will be used to synchronize access to the |
| 871 | value. If *lock* is ``False`` then access to the returned object will not be |
| 872 | automatically protected by a lock, so it will not necessarily be |
| 873 | "process-safe". |
| 874 | |
| 875 | Note that *lock* is a keyword only argument. |
| 876 | |
| 877 | Note that an array of :data:`ctypes.c_char` has *value* and *rawvalue* |
| 878 | attributes which allow one to use it to store and retrieve strings. |
| 879 | |
| 880 | |
| 881 | The :mod:`multiprocessing.sharedctypes` module |
| 882 | >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> |
| 883 | |
| 884 | .. module:: multiprocessing.sharedctypes |
| 885 | :synopsis: Allocate ctypes objects from shared memory. |
| 886 | |
| 887 | The :mod:`multiprocessing.sharedctypes` module provides functions for allocating |
| 888 | :mod:`ctypes` objects from shared memory which can be inherited by child |
| 889 | processes. |
| 890 | |
| 891 | .. note:: |
| 892 | |
| 893 | Although it is posible to store a pointer in shared memory remember that this |
| 894 | will refer to a location in the address space of a specific process. |
| 895 | However, the pointer is quite likely to be invalid in the context of a second |
| 896 | process and trying to dereference the pointer from the second process may |
| 897 | cause a crash. |
| 898 | |
| 899 | .. function:: RawArray(typecode_or_type, size_or_initializer) |
| 900 | |
| 901 | Return a ctypes array allocated from shared memory. |
| 902 | |
| 903 | *typecode_or_type* determines the type of the elements of the returned array: |
| 904 | it is either a ctypes type or a one character typecode of the kind used by |
| 905 | the :mod:`array` module. If *size_or_initializer* is an integer then it |
| 906 | determines the length of the array, and the array will be initially zeroed. |
| 907 | Otherwise *size_or_initializer* is a sequence which is used to initialize the |
| 908 | array and whose length determines the length of the array. |
| 909 | |
| 910 | Note that setting and getting an element is potentially non-atomic -- use |
| 911 | :func:`Array` instead to make sure that access is automatically synchronized |
| 912 | using a lock. |
| 913 | |
| 914 | .. function:: RawValue(typecode_or_type, *args) |
| 915 | |
| 916 | Return a ctypes object allocated from shared memory. |
| 917 | |
| 918 | *typecode_or_type* determines the type of the returned object: it is either a |
| 919 | ctypes type or a one character typecode of the kind used by the :mod:`array` |
| 920 | module. */*args* is passed on to the constructor for the type. |
| 921 | |
| 922 | Note that setting and getting the value is potentially non-atomic -- use |
| 923 | :func:`Value` instead to make sure that access is automatically synchronized |
| 924 | using a lock. |
| 925 | |
| 926 | Note that an array of :data:`ctypes.c_char` has ``value`` and ``rawvalue`` |
| 927 | attributes which allow one to use it to store and retrieve strings -- see |
| 928 | documentation for :mod:`ctypes`. |
| 929 | |
| 930 | .. function:: Array(typecode_or_type, size_or_initializer[, lock[, *args]]) |
| 931 | |
| 932 | The same as :func:`RawArray` except that depending on the value of *lock* a |
| 933 | process-safe synchronization wrapper may be returned instead of a raw ctypes |
| 934 | array. |
| 935 | |
| 936 | If *lock* is ``True`` (the default) then a new lock object is created to |
| 937 | synchronize access to the value. If *lock* is a :class:`Lock` or |
| 938 | :class:`RLock` object then that will be used to synchronize access to the |
| 939 | value. If *lock* is ``False`` then access to the returned object will not be |
| 940 | automatically protected by a lock, so it will not necessarily be |
| 941 | "process-safe". |
| 942 | |
| 943 | Note that *lock* is a keyword-only argument. |
| 944 | |
| 945 | .. function:: Value(typecode_or_type, *args[, lock]) |
| 946 | |
| 947 | The same as :func:`RawValue` except that depending on the value of *lock* a |
| 948 | process-safe synchronization wrapper may be returned instead of a raw ctypes |
| 949 | object. |
| 950 | |
| 951 | If *lock* is ``True`` (the default) then a new lock object is created to |
| 952 | synchronize access to the value. If *lock* is a :class:`Lock` or |
| 953 | :class:`RLock` object then that will be used to synchronize access to the |
| 954 | value. If *lock* is ``False`` then access to the returned object will not be |
| 955 | automatically protected by a lock, so it will not necessarily be |
| 956 | "process-safe". |
| 957 | |
| 958 | Note that *lock* is a keyword-only argument. |
| 959 | |
| 960 | .. function:: copy(obj) |
| 961 | |
| 962 | Return a ctypes object allocated from shared memory which is a copy of the |
| 963 | ctypes object *obj*. |
| 964 | |
| 965 | .. function:: synchronized(obj[, lock]) |
| 966 | |
| 967 | Return a process-safe wrapper object for a ctypes object which uses *lock* to |
| 968 | synchronize access. If *lock* is ``None`` (the default) then a |
| 969 | :class:`multiprocessing.RLock` object is created automatically. |
| 970 | |
| 971 | A synchronized wrapper will have two methods in addition to those of the |
| 972 | object it wraps: :meth:`get_obj()` returns the wrapped object and |
| 973 | :meth:`get_lock()` returns the lock object used for synchronization. |
| 974 | |
| 975 | Note that accessing the ctypes object through the wrapper can be a lot slower |
| 976 | han accessing the raw ctypes object. |
| 977 | |
| 978 | |
| 979 | The table below compares the syntax for creating shared ctypes objects from |
| 980 | shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some |
| 981 | subclass of :class:`ctypes.Structure`.) |
| 982 | |
| 983 | ==================== ========================== =========================== |
| 984 | ctypes sharedctypes using type sharedctypes using typecode |
| 985 | ==================== ========================== =========================== |
| 986 | c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4) |
| 987 | MyStruct(4, 6) RawValue(MyStruct, 4, 6) |
| 988 | (c_short * 7)() RawArray(c_short, 7) RawArray('h', 7) |
| 989 | (c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8)) |
| 990 | ==================== ========================== =========================== |
| 991 | |
| 992 | |
| 993 | Below is an example where a number of ctypes objects are modified by a child |
| 994 | process:: |
| 995 | |
| 996 | from multiprocessing import Process, Lock |
| 997 | from multiprocessing.sharedctypes import Value, Array |
| 998 | from ctypes import Structure, c_double |
| 999 | |
| 1000 | class Point(Structure): |
| 1001 | _fields_ = [('x', c_double), ('y', c_double)] |
| 1002 | |
| 1003 | def modify(n, x, s, A): |
| 1004 | n.value **= 2 |
| 1005 | x.value **= 2 |
| 1006 | s.value = s.value.upper() |
| 1007 | for a in A: |
| 1008 | a.x **= 2 |
| 1009 | a.y **= 2 |
| 1010 | |
| 1011 | if __name__ == '__main__': |
| 1012 | lock = Lock() |
| 1013 | |
| 1014 | n = Value('i', 7) |
| 1015 | x = Value(ctypes.c_double, 1.0/3.0, lock=False) |
| 1016 | s = Array('c', 'hello world', lock=lock) |
| 1017 | A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock) |
| 1018 | |
| 1019 | p = Process(target=modify, args=(n, x, s, A)) |
| 1020 | p.start() |
| 1021 | p.join() |
| 1022 | |
| 1023 | print n.value |
| 1024 | print x.value |
| 1025 | print s.value |
| 1026 | print [(a.x, a.y) for a in A] |
| 1027 | |
| 1028 | |
| 1029 | .. highlightlang:: none |
| 1030 | |
| 1031 | The results printed are :: |
| 1032 | |
| 1033 | 49 |
| 1034 | 0.1111111111111111 |
| 1035 | HELLO WORLD |
| 1036 | [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)] |
| 1037 | |
| 1038 | .. highlightlang:: python |
| 1039 | |
| 1040 | |
| 1041 | .. _multiprocessing-managers: |
| 1042 | |
| 1043 | Managers |
| 1044 | ~~~~~~~~ |
| 1045 | |
| 1046 | Managers provide a way to create data which can be shared between different |
| 1047 | processes. A manager object controls a server process which manages *shared |
| 1048 | objects*. Other processes can access the shared objects by using proxies. |
| 1049 | |
| 1050 | .. function:: multiprocessing.Manager() |
| 1051 | |
| 1052 | Returns a started :class:`SyncManager` object which can be used for sharing |
| 1053 | objects between processes. The returned manager object corresponds to a |
| 1054 | spawned child process and has methods which will create shared objects and |
| 1055 | return corresponding proxies. |
| 1056 | |
| 1057 | .. module:: multiprocessing.managers |
| 1058 | :synopsis: Share data between process with shared objects. |
| 1059 | |
| 1060 | Manager processes will be shutdown as soon as they are garbage collected or |
| 1061 | their parent process exits. The manager classes are defined in the |
| 1062 | :mod:`multiprocessing.managers` module: |
| 1063 | |
| 1064 | .. class:: BaseManager([address[, authkey]]) |
| 1065 | |
| 1066 | Create a BaseManager object. |
| 1067 | |
| 1068 | Once created one should call :meth:`start` or :meth:`serve_forever` to ensure |
| 1069 | that the manager object refers to a started manager process. |
| 1070 | |
| 1071 | *address* is the address on which the manager process listens for new |
| 1072 | connections. If *address* is ``None`` then an arbitrary one is chosen. |
| 1073 | |
| 1074 | *authkey* is the authentication key which will be used to check the validity |
| 1075 | of incoming connections to the server process. If *authkey* is ``None`` then |
| 1076 | ``current_process().get_auth_key()``. Otherwise *authkey* is used and it |
| 1077 | must be a string. |
| 1078 | |
| 1079 | .. method:: start() |
| 1080 | |
| 1081 | Start a subprocess to start the manager. |
| 1082 | |
| 1083 | .. method:: server_forever() |
| 1084 | |
| 1085 | Run the server in the current process. |
| 1086 | |
| 1087 | .. method:: from_address(address, authkey) |
| 1088 | |
| 1089 | A class method which creates a manager object referring to a pre-existing |
| 1090 | server process which is using the given address and authentication key. |
| 1091 | |
| 1092 | .. method:: shutdown() |
| 1093 | |
| 1094 | Stop the process used by the manager. This is only available if |
| 1095 | meth:`start` has been used to start the server process. |
| 1096 | |
| 1097 | This can be called multiple times. |
| 1098 | |
| 1099 | .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]]) |
| 1100 | |
| 1101 | A classmethod which can be used for registering a type or callable with |
| 1102 | the manager class. |
| 1103 | |
| 1104 | *typeid* is a "type identifier" which is used to identify a particular |
| 1105 | type of shared object. This must be a string. |
| 1106 | |
| 1107 | *callable* is a callable used for creating objects for this type |
| 1108 | identifier. If a manager instance will be created using the |
| 1109 | :meth:`from_address()` classmethod or if the *create_method* argument is |
| 1110 | ``False`` then this can be left as ``None``. |
| 1111 | |
| 1112 | *proxytype* is a subclass of :class:`multiprocessing.managers.BaseProxy` |
| 1113 | which is used to create proxies for shared objects with this *typeid*. If |
| 1114 | ``None`` then a proxy class is created automatically. |
| 1115 | |
| 1116 | *exposed* is used to specify a sequence of method names which proxies for |
| 1117 | this typeid should be allowed to access using |
| 1118 | :meth:`BaseProxy._callMethod`. (If *exposed* is ``None`` then |
| 1119 | :attr:`proxytype._exposed_` is used instead if it exists.) In the case |
| 1120 | where no exposed list is specified, all "public methods" of the shared |
| 1121 | object will be accessible. (Here a "public method" means any attribute |
| 1122 | which has a ``__call__()`` method and whose name does not begin with |
| 1123 | ``'_'``.) |
| 1124 | |
| 1125 | *method_to_typeid* is a mapping used to specify the return type of those |
| 1126 | exposed methods which should return a proxy. It maps method names to |
| 1127 | typeid strings. (If *method_to_typeid* is ``None`` then |
| 1128 | :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a |
| 1129 | method's name is not a key of this mapping or if the mapping is ``None`` |
| 1130 | then the object returned by the method will be copied by value. |
| 1131 | |
| 1132 | *create_method* determines whether a method should be created with name |
| 1133 | *typeid* which can be used to tell the server process to create a new |
| 1134 | shared object and return a proxy for it. By default it is ``True``. |
| 1135 | |
| 1136 | :class:`BaseManager` instances also have one read-only property: |
| 1137 | |
| 1138 | .. attribute:: address |
| 1139 | |
| 1140 | The address used by the manager. |
| 1141 | |
| 1142 | |
| 1143 | .. class:: SyncManager |
| 1144 | |
| 1145 | A subclass of :class:`BaseManager` which can be used for the synchronization |
| 1146 | of processes. Objects of this type are returned by |
| 1147 | :func:`multiprocessing.Manager()`. |
| 1148 | |
| 1149 | It also supports creation of shared lists and dictionaries. |
| 1150 | |
| 1151 | .. method:: BoundedSemaphore([value]) |
| 1152 | |
| 1153 | Create a shared :class:`threading.BoundedSemaphore` object and return a |
| 1154 | proxy for it. |
| 1155 | |
| 1156 | .. method:: Condition([lock]) |
| 1157 | |
| 1158 | Create a shared :class:`threading.Condition` object and return a proxy for |
| 1159 | it. |
| 1160 | |
| 1161 | If *lock* is supplied then it should be a proxy for a |
| 1162 | :class:`threading.Lock` or :class:`threading.RLock` object. |
| 1163 | |
| 1164 | .. method:: Event() |
| 1165 | |
| 1166 | Create a shared :class:`threading.Event` object and return a proxy for it. |
| 1167 | |
| 1168 | .. method:: Lock() |
| 1169 | |
| 1170 | Create a shared :class:`threading.Lock` object and return a proxy for it. |
| 1171 | |
| 1172 | .. method:: Namespace() |
| 1173 | |
| 1174 | Create a shared :class:`Namespace` object and return a proxy for it. |
| 1175 | |
| 1176 | .. method:: Queue([maxsize]) |
| 1177 | |
| 1178 | Create a shared `Queue.Queue` object and return a proxy for it. |
| 1179 | |
| 1180 | .. method:: RLock() |
| 1181 | |
| 1182 | Create a shared :class:`threading.RLock` object and return a proxy for it. |
| 1183 | |
| 1184 | .. method:: Semaphore([value]) |
| 1185 | |
| 1186 | Create a shared :class:`threading.Semaphore` object and return a proxy for |
| 1187 | it. |
| 1188 | |
| 1189 | .. method:: Array(typecode, sequence) |
| 1190 | |
| 1191 | Create an array and return a proxy for it. (*format* is ignored.) |
| 1192 | |
| 1193 | .. method:: Value(typecode, value) |
| 1194 | |
| 1195 | Create an object with a writable ``value`` attribute and return a proxy |
| 1196 | for it. |
| 1197 | |
| 1198 | .. method:: dict() |
| 1199 | dict(mapping) |
| 1200 | dict(sequence) |
| 1201 | |
| 1202 | Create a shared ``dict`` object and return a proxy for it. |
| 1203 | |
| 1204 | .. method:: list() |
| 1205 | list(sequence) |
| 1206 | |
| 1207 | Create a shared ``list`` object and return a proxy for it. |
| 1208 | |
| 1209 | |
| 1210 | Namespace objects |
| 1211 | >>>>>>>>>>>>>>>>> |
| 1212 | |
| 1213 | A namespace object has no public methods, but does have writable attributes. |
| 1214 | Its representation shows the values of its attributes. |
| 1215 | |
| 1216 | However, when using a proxy for a namespace object, an attribute beginning with |
| 1217 | ``'_'`` will be an attribute of the proxy and not an attribute of the referent:: |
| 1218 | |
| 1219 | >>> manager = multiprocessing.Manager() |
| 1220 | >>> Global = manager.Namespace() |
| 1221 | >>> Global.x = 10 |
| 1222 | >>> Global.y = 'hello' |
| 1223 | >>> Global._z = 12.3 # this is an attribute of the proxy |
| 1224 | >>> print Global |
| 1225 | Namespace(x=10, y='hello') |
| 1226 | |
| 1227 | |
| 1228 | Customized managers |
| 1229 | >>>>>>>>>>>>>>>>>>> |
| 1230 | |
| 1231 | To create one's own manager, one creates a subclass of :class:`BaseManager` and |
| 1232 | use the :meth:`resgister()` classmethod to register new types or callables with |
| 1233 | the manager class. For example:: |
| 1234 | |
| 1235 | from multiprocessing.managers import BaseManager |
| 1236 | |
| 1237 | class MathsClass(object): |
| 1238 | def add(self, x, y): |
| 1239 | return x + y |
| 1240 | def mul(self, x, y): |
| 1241 | return x * y |
| 1242 | |
| 1243 | class MyManager(BaseManager): |
| 1244 | pass |
| 1245 | |
| 1246 | MyManager.register('Maths', MathsClass) |
| 1247 | |
| 1248 | if __name__ == '__main__': |
| 1249 | manager = MyManager() |
| 1250 | manager.start() |
| 1251 | maths = manager.Maths() |
| 1252 | print maths.add(4, 3) # prints 7 |
| 1253 | print maths.mul(7, 8) # prints 56 |
| 1254 | |
| 1255 | |
| 1256 | Using a remote manager |
| 1257 | >>>>>>>>>>>>>>>>>>>>>> |
| 1258 | |
| 1259 | It is possible to run a manager server on one machine and have clients use it |
| 1260 | from other machines (assuming that the firewalls involved allow it). |
| 1261 | |
| 1262 | Running the following commands creates a server for a single shared queue which |
| 1263 | remote clients can access:: |
| 1264 | |
| 1265 | >>> from multiprocessing.managers import BaseManager |
| 1266 | >>> import Queue |
| 1267 | >>> queue = Queue.Queue() |
| 1268 | >>> class QueueManager(BaseManager): pass |
| 1269 | ... |
| 1270 | >>> QueueManager.register('getQueue', callable=lambda:queue) |
| 1271 | >>> m = QueueManager(address=('', 50000), authkey='abracadabra') |
| 1272 | >>> m.serveForever() |
| 1273 | |
| 1274 | One client can access the server as follows:: |
| 1275 | |
| 1276 | >>> from multiprocessing.managers import BaseManager |
| 1277 | >>> class QueueManager(BaseManager): pass |
| 1278 | ... |
| 1279 | >>> QueueManager.register('getQueue') |
| 1280 | >>> m = QueueManager.from_address(address=('foo.bar.org', 50000), |
| 1281 | >>> authkey='abracadabra') |
| 1282 | >>> queue = m.getQueue() |
| 1283 | >>> queue.put('hello') |
| 1284 | |
| 1285 | Another client can also use it:: |
| 1286 | |
| 1287 | >>> from multiprocessing.managers import BaseManager |
| 1288 | >>> class QueueManager(BaseManager): pass |
| 1289 | ... |
| 1290 | >>> QueueManager.register('getQueue') |
| 1291 | >>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='abracadabra') |
| 1292 | >>> queue = m.getQueue() |
| 1293 | >>> queue.get() |
| 1294 | 'hello' |
| 1295 | |
| 1296 | |
| 1297 | Proxy Objects |
| 1298 | ~~~~~~~~~~~~~ |
| 1299 | |
| 1300 | A proxy is an object which *refers* to a shared object which lives (presumably) |
| 1301 | in a different process. The shared object is said to be the *referent* of the |
| 1302 | proxy. Multiple proxy objects may have the same referent. |
| 1303 | |
| 1304 | A proxy object has methods which invoke corresponding methods of its referent |
| 1305 | (although not every method of the referent will necessarily be available through |
| 1306 | the proxy). A proxy can usually be used in most of the same ways that its |
| 1307 | referent can:: |
| 1308 | |
| 1309 | >>> from multiprocessing import Manager |
| 1310 | >>> manager = Manager() |
| 1311 | >>> l = manager.list([i*i for i in range(10)]) |
| 1312 | >>> print l |
| 1313 | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
| 1314 | >>> print repr(l) |
| 1315 | <ListProxy object, typeid 'list' at 0xb799974c> |
| 1316 | >>> l[4] |
| 1317 | 16 |
| 1318 | >>> l[2:5] |
| 1319 | [4, 9, 16] |
| 1320 | |
| 1321 | Notice that applying :func:`str` to a proxy will return the representation of |
| 1322 | the referent, whereas applying :func:`repr` will return the representation of |
| 1323 | the proxy. |
| 1324 | |
| 1325 | An important feature of proxy objects is that they are picklable so they can be |
| 1326 | passed between processes. Note, however, that if a proxy is sent to the |
| 1327 | corresponding manager's process then unpickling it will produce the referent |
| 1328 | itself. This means, for example, that one shared object can contain a second:: |
| 1329 | |
| 1330 | >>> a = manager.list() |
| 1331 | >>> b = manager.list() |
| 1332 | >>> a.append(b) # referent of `a` now contains referent of `b` |
| 1333 | >>> print a, b |
| 1334 | [[]] [] |
| 1335 | >>> b.append('hello') |
| 1336 | >>> print a, b |
| 1337 | [['hello']] ['hello'] |
| 1338 | |
| 1339 | .. note:: |
| 1340 | |
| 1341 | The proxy types in :mod:`multiprocessing` do nothing to support comparisons |
| 1342 | by value. So, for instance, :: |
| 1343 | |
| 1344 | manager.list([1,2,3]) == [1,2,3] |
| 1345 | |
| 1346 | will return ``False``. One should just use a copy of the referent instead |
| 1347 | when making comparisons. |
| 1348 | |
| 1349 | .. class:: BaseProxy |
| 1350 | |
| 1351 | Proxy objects are instances of subclasses of :class:`BaseProxy`. |
| 1352 | |
| 1353 | .. method:: _call_method(methodname[, args[, kwds]]) |
| 1354 | |
| 1355 | Call and return the result of a method of the proxy's referent. |
| 1356 | |
| 1357 | If ``proxy`` is a proxy whose referent is ``obj`` then the expression :: |
| 1358 | |
| 1359 | proxy._call_method(methodname, args, kwds) |
| 1360 | |
| 1361 | will evaluate the expression :: |
| 1362 | |
| 1363 | getattr(obj, methodname)(*args, **kwds) |
| 1364 | |
| 1365 | in the manager's process. |
| 1366 | |
| 1367 | The returned value will be a copy of the result of the call or a proxy to |
| 1368 | a new shared object -- see documentation for the *method_to_typeid* |
| 1369 | argument of :meth:`BaseManager.register`. |
| 1370 | |
| 1371 | If an exception is raised by the call, then then is re-raised by |
| 1372 | :meth:`_call_method`. If some other exception is raised in the manager's |
| 1373 | process then this is converted into a :exc:`RemoteError` exception and is |
| 1374 | raised by :meth:`_call_method`. |
| 1375 | |
| 1376 | Note in particular that an exception will be raised if *methodname* has |
| 1377 | not been *exposed* |
| 1378 | |
| 1379 | An example of the usage of :meth:`_call_method()`:: |
| 1380 | |
| 1381 | >>> l = manager.list(range(10)) |
| 1382 | >>> l._call_method('__len__') |
| 1383 | 10 |
| 1384 | >>> l._call_method('__getslice__', (2, 7)) # equiv to `l[2:7]` |
| 1385 | [2, 3, 4, 5, 6] |
| 1386 | >>> l._call_method('__getitem__', (20,)) # equiv to `l[20]` |
| 1387 | Traceback (most recent call last): |
| 1388 | ... |
| 1389 | IndexError: list index out of range |
| 1390 | |
| 1391 | .. method:: _get_value() |
| 1392 | |
| 1393 | Return a copy of the referent. |
| 1394 | |
| 1395 | If the referent is unpicklable then this will raise an exception. |
| 1396 | |
| 1397 | .. method:: __repr__ |
| 1398 | |
| 1399 | Return a representation of the proxy object. |
| 1400 | |
| 1401 | .. method:: __str__ |
| 1402 | |
| 1403 | Return the representation of the referent. |
| 1404 | |
| 1405 | |
| 1406 | Cleanup |
| 1407 | >>>>>>> |
| 1408 | |
| 1409 | A proxy object uses a weakref callback so that when it gets garbage collected it |
| 1410 | deregisters itself from the manager which owns its referent. |
| 1411 | |
| 1412 | A shared object gets deleted from the manager process when there are no longer |
| 1413 | any proxies referring to it. |
| 1414 | |
| 1415 | |
| 1416 | Process Pools |
| 1417 | ~~~~~~~~~~~~~ |
| 1418 | |
| 1419 | .. module:: multiprocessing.pool |
| 1420 | :synopsis: Create pools of processes. |
| 1421 | |
| 1422 | One can create a pool of processes which will carry out tasks submitted to it |
| 1423 | with the :class:`Pool` class in :mod:`multiprocess.pool`. |
| 1424 | |
| 1425 | .. class:: multiprocessing.Pool([processes[, initializer[, initargs]]]) |
| 1426 | |
| 1427 | A process pool object which controls a pool of worker processes to which jobs |
| 1428 | can be submitted. It supports asynchronous results with timeouts and |
| 1429 | callbacks and has a parallel map implementation. |
| 1430 | |
| 1431 | *processes* is the number of worker processes to use. If *processes* is |
| 1432 | ``None`` then the number returned by :func:`cpu_count` is used. If |
| 1433 | *initializer* is not ``None`` then each worker process will call |
| 1434 | ``initializer(*initargs)`` when it starts. |
| 1435 | |
| 1436 | .. method:: apply(func[, args[, kwds]]) |
| 1437 | |
| 1438 | Equivalent of the :func:`apply` builtin function. It blocks till the |
| 1439 | result is ready. |
| 1440 | |
| 1441 | .. method:: apply_async(func[, args[, kwds[, callback]]]) |
| 1442 | |
| 1443 | A variant of the :meth:`apply` method which returns a result object. |
| 1444 | |
| 1445 | If *callback* is specified then it should be a callable which accepts a |
| 1446 | single argument. When the result becomes ready *callback* is applied to |
| 1447 | it (unless the call failed). *callback* should complete immediately since |
| 1448 | otherwise the thread which handles the results will get blocked. |
| 1449 | |
| 1450 | .. method:: map(func, iterable[, chunksize]) |
| 1451 | |
| 1452 | A parallel equivalent of the :func:`map` builtin function. It blocks till |
| 1453 | the result is ready. |
| 1454 | |
| 1455 | This method chops the iterable into a number of chunks which it submits to |
| 1456 | the process pool as separate tasks. The (approximate) size of these |
| 1457 | chunks can be specified by setting *chunksize* to a positive integer. |
| 1458 | |
| 1459 | .. method:: map_async(func, iterable[, chunksize[, callback]]) |
| 1460 | |
| 1461 | A variant of the :meth:`.map` method which returns a result object. |
| 1462 | |
| 1463 | If *callback* is specified then it should be a callable which accepts a |
| 1464 | single argument. When the result becomes ready *callback* is applied to |
| 1465 | it (unless the call failed). *callback* should complete immediately since |
| 1466 | otherwise the thread which handles the results will get blocked. |
| 1467 | |
| 1468 | .. method:: imap(func, iterable[, chunksize]) |
| 1469 | |
| 1470 | An equivalent of :func:`itertools.imap`. |
| 1471 | |
| 1472 | The *chunksize* argument is the same as the one used by the :meth:`.map` |
| 1473 | method. For very long iterables using a large value for *chunksize* can |
| 1474 | make make the job complete **much** faster than using the default value of |
| 1475 | ``1``. |
| 1476 | |
| 1477 | Also if *chunksize* is ``1`` then the :meth:`next` method of the iterator |
| 1478 | returned by the :meth:`imap` method has an optional *timeout* parameter: |
| 1479 | ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the |
| 1480 | result cannot be returned within *timeout* seconds. |
| 1481 | |
| 1482 | .. method:: imap_unordered(func, iterable[, chunksize]) |
| 1483 | |
| 1484 | The same as :meth:`imap` except that the ordering of the results from the |
| 1485 | returned iterator should be considered arbitrary. (Only when there is |
| 1486 | only one worker process is the order guaranteed to be "correct".) |
| 1487 | |
| 1488 | .. method:: close() |
| 1489 | |
| 1490 | Prevents any more tasks from being submitted to the pool. Once all the |
| 1491 | tasks have been completed the worker processes will exit. |
| 1492 | |
| 1493 | .. method:: terminate() |
| 1494 | |
| 1495 | Stops the worker processes immediately without completing outstanding |
| 1496 | work. When the pool object is garbage collected :meth:`terminate` will be |
| 1497 | called immediately. |
| 1498 | |
| 1499 | .. method:: join() |
| 1500 | |
| 1501 | Wait for the worker processes to exit. One must call :meth:`close` or |
| 1502 | :meth:`terminate` before using :meth:`join`. |
| 1503 | |
| 1504 | |
| 1505 | .. class:: AsyncResult |
| 1506 | |
| 1507 | The class of the result returned by :meth:`Pool.apply_async` and |
| 1508 | :meth:`Pool.map_async`. |
| 1509 | |
| 1510 | .. method:: get([timeout) |
| 1511 | |
| 1512 | Return the result when it arrives. If *timeout* is not ``None`` and the |
| 1513 | result does not arrive within *timeout* seconds then |
| 1514 | :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised |
| 1515 | an exception then that exception will be reraised by :meth:`get`. |
| 1516 | |
| 1517 | .. method:: wait([timeout]) |
| 1518 | |
| 1519 | Wait until the result is available or until *timeout* seconds pass. |
| 1520 | |
| 1521 | .. method:: ready() |
| 1522 | |
| 1523 | Return whether the call has completed. |
| 1524 | |
| 1525 | .. method:: successful() |
| 1526 | |
| 1527 | Return whether the call completed without raising an exception. Will |
| 1528 | raise :exc:`AssertionError` if the result is not ready. |
| 1529 | |
| 1530 | The following example demonstrates the use of a pool:: |
| 1531 | |
| 1532 | from multiprocessing import Pool |
| 1533 | |
| 1534 | def f(x): |
| 1535 | return x*x |
| 1536 | |
| 1537 | if __name__ == '__main__': |
| 1538 | pool = Pool(processes=4) # start 4 worker processes |
| 1539 | |
| 1540 | result = pool.applyAsync(f, (10,)) # evaluate "f(10)" asynchronously |
| 1541 | print result.get(timeout=1) # prints "100" unless your computer is *very* slow |
| 1542 | |
| 1543 | print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" |
| 1544 | |
| 1545 | it = pool.imap(f, range(10)) |
| 1546 | print it.next() # prints "0" |
| 1547 | print it.next() # prints "1" |
| 1548 | print it.next(timeout=1) # prints "4" unless your computer is *very* slow |
| 1549 | |
| 1550 | import time |
| 1551 | result = pool.applyAsync(time.sleep, (10,)) |
| 1552 | print result.get(timeout=1) # raises TimeoutError |
| 1553 | |
| 1554 | |
| 1555 | .. _multiprocessing-listeners-clients: |
| 1556 | |
| 1557 | Listeners and Clients |
| 1558 | ~~~~~~~~~~~~~~~~~~~~~ |
| 1559 | |
| 1560 | .. module:: multiprocessing.connection |
| 1561 | :synopsis: API for dealing with sockets. |
| 1562 | |
| 1563 | Usually message passing between processes is done using queues or by using |
| 1564 | :class:`Connection` objects returned by :func:`Pipe`. |
| 1565 | |
| 1566 | However, the :mod:`multiprocessing.connection` module allows some extra |
| 1567 | flexibility. It basically gives a high level message oriented API for dealing |
| 1568 | with sockets or Windows named pipes, and also has support for *digest |
| 1569 | authentication* using the :mod:`hmac` module from the standard library. |
| 1570 | |
| 1571 | |
| 1572 | .. function:: deliver_challenge(connection, authkey) |
| 1573 | |
| 1574 | Send a randomly generated message to the other end of the connection and wait |
| 1575 | for a reply. |
| 1576 | |
| 1577 | If the reply matches the digest of the message using *authkey* as the key |
| 1578 | then a welcome message is sent to the other end of the connection. Otherwise |
| 1579 | :exc:`AuthenticationError` is raised. |
| 1580 | |
| 1581 | .. function:: answerChallenge(connection, authkey) |
| 1582 | |
| 1583 | Receive a message, calculate the digest of the message using *authkey* as the |
| 1584 | key, and then send the digest back. |
| 1585 | |
| 1586 | If a welcome message is not received, then :exc:`AuthenticationError` is |
| 1587 | raised. |
| 1588 | |
| 1589 | .. function:: Client(address[, family[, authenticate[, authkey]]]) |
| 1590 | |
| 1591 | Attempt to set up a connection to the listener which is using address |
| 1592 | *address*, returning a :class:`Connection`. |
| 1593 | |
| 1594 | The type of the connection is determined by *family* argument, but this can |
| 1595 | generally be omitted since it can usually be inferred from the format of |
| 1596 | *address*. (See :ref:`multiprocessing-address-formats`) |
| 1597 | |
| 1598 | If *authentication* is ``True`` or *authkey* is a string then digest |
| 1599 | authentication is used. The key used for authentication will be either |
| 1600 | *authkey* or ``current_process().get_auth_key()`` if *authkey* is ``None``. |
| 1601 | If authentication fails then :exc:`AuthenticationError` is raised. See |
| 1602 | :ref:`multiprocessing-auth-keys`. |
| 1603 | |
| 1604 | .. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]]) |
| 1605 | |
| 1606 | A wrapper for a bound socket or Windows named pipe which is 'listening' for |
| 1607 | connections. |
| 1608 | |
| 1609 | *address* is the address to be used by the bound socket or named pipe of the |
| 1610 | listener object. |
| 1611 | |
| 1612 | *family* is the type of socket (or named pipe) to use. This can be one of |
| 1613 | the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix |
| 1614 | domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only |
| 1615 | the first is guaranteed to be available. If *family* is ``None`` then the |
| 1616 | family is inferred from the format of *address*. If *address* is also |
| 1617 | ``None`` then a default is chosen. This default is the family which is |
| 1618 | assumed to be the fastest available. See |
| 1619 | :ref:`multiprocessing-address-formats`. Note that if *family* is |
| 1620 | ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a |
| 1621 | private temporary directory created using :func:`tempfile.mkstemp`. |
| 1622 | |
| 1623 | If the listener object uses a socket then *backlog* (1 by default) is passed |
| 1624 | to the :meth:`listen` method of the socket once it has been bound. |
| 1625 | |
| 1626 | If *authenticate* is ``True`` (``False`` by default) or *authkey* is not |
| 1627 | ``None`` then digest authentication is used. |
| 1628 | |
| 1629 | If *authkey* is a string then it will be used as the authentication key; |
| 1630 | otherwise it must be *None*. |
| 1631 | |
| 1632 | If *authkey* is ``None`` and *authenticate* is ``True`` then |
| 1633 | ``current_process().get_auth_key()`` is used as the authentication key. If |
| 1634 | *authkey* is ``None`` and *authentication* is ``False`` then no |
| 1635 | authentication is done. If authentication fails then |
| 1636 | :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`. |
| 1637 | |
| 1638 | .. method:: accept() |
| 1639 | |
| 1640 | Accept a connection on the bound socket or named pipe of the listener |
| 1641 | object and return a :class:`Connection` object. If authentication is |
| 1642 | attempted and fails, then :exc:`AuthenticationError` is raised. |
| 1643 | |
| 1644 | .. method:: close() |
| 1645 | |
| 1646 | Close the bound socket or named pipe of the listener object. This is |
| 1647 | called automatically when the listener is garbage collected. However it |
| 1648 | is advisable to call it explicitly. |
| 1649 | |
| 1650 | Listener objects have the following read-only properties: |
| 1651 | |
| 1652 | .. attribute:: address |
| 1653 | |
| 1654 | The address which is being used by the Listener object. |
| 1655 | |
| 1656 | .. attribute:: last_accepted |
| 1657 | |
| 1658 | The address from which the last accepted connection came. If this is |
| 1659 | unavailable then it is ``None``. |
| 1660 | |
| 1661 | |
| 1662 | The module defines two exceptions: |
| 1663 | |
| 1664 | .. exception:: AuthenticationError |
| 1665 | |
| 1666 | Exception raised when there is an authentication error. |
| 1667 | |
| 1668 | .. exception:: BufferTooShort |
| 1669 | |
| 1670 | Exception raise by the :meth:`Connection.recv_bytes_into` method of a |
| 1671 | connection object when the supplied buffer object is too small for the |
| 1672 | message read. |
| 1673 | |
| 1674 | If *e* is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give |
| 1675 | the message as a byte string. |
| 1676 | |
| 1677 | |
| 1678 | **Examples** |
| 1679 | |
| 1680 | The following server code creates a listener which uses ``'secret password'`` as |
| 1681 | an authentication key. It then waits for a connection and sends some data to |
| 1682 | the client:: |
| 1683 | |
| 1684 | from multiprocessing.connection import Listener |
| 1685 | from array import array |
| 1686 | |
| 1687 | address = ('localhost', 6000) # family is deduced to be 'AF_INET' |
| 1688 | listener = Listener(address, authkey='secret password') |
| 1689 | |
| 1690 | conn = listener.accept() |
| 1691 | print 'connection accepted from', listener.last_accepted |
| 1692 | |
| 1693 | conn.send([2.25, None, 'junk', float]) |
| 1694 | |
| 1695 | conn.send_bytes('hello') |
| 1696 | |
| 1697 | conn.send_bytes(array('i', [42, 1729])) |
| 1698 | |
| 1699 | conn.close() |
| 1700 | listener.close() |
| 1701 | |
| 1702 | The following code connects to the server and receives some data from the |
| 1703 | server:: |
| 1704 | |
| 1705 | from multiprocessing.connection import Client |
| 1706 | from array import array |
| 1707 | |
| 1708 | address = ('localhost', 6000) |
| 1709 | conn = Client(address, authkey='secret password') |
| 1710 | |
| 1711 | print conn.recv() # => [2.25, None, 'junk', float] |
| 1712 | |
| 1713 | print conn.recv_bytes() # => 'hello' |
| 1714 | |
| 1715 | arr = array('i', [0, 0, 0, 0, 0]) |
| 1716 | print conn.recv_bytes_into(arr) # => 8 |
| 1717 | print arr # => array('i', [42, 1729, 0, 0, 0]) |
| 1718 | |
| 1719 | conn.close() |
| 1720 | |
| 1721 | |
| 1722 | .. _multiprocessing-address-formats: |
| 1723 | |
| 1724 | Address Formats |
| 1725 | >>>>>>>>>>>>>>> |
| 1726 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 1727 | * An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 1728 | *hostname* is a string and *port* is an integer. |
| 1729 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 1730 | * An ``'AF_UNIX'`` address is a string representing a filename on the |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 1731 | filesystem. |
| 1732 | |
| 1733 | * An ``'AF_PIPE'`` address is a string of the form |
| 1734 | ``r'\\\\.\\pipe\\PipeName'``. To use :func:`Client` to connect to a named |
| 1735 | pipe on a remote computer called ServerName* one should use an address of the |
| 1736 | form ``r'\\\\ServerName\\pipe\\PipeName'`` instead. |
| 1737 | |
| 1738 | Note that any string beginning with two backslashes is assumed by default to be |
| 1739 | an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address. |
| 1740 | |
| 1741 | |
| 1742 | .. _multiprocessing-auth-keys: |
| 1743 | |
| 1744 | Authentication keys |
| 1745 | ~~~~~~~~~~~~~~~~~~~ |
| 1746 | |
| 1747 | When one uses :meth:`Connection.recv`, the data received is automatically |
| 1748 | unpickled. Unfortunately unpickling data from an untrusted source is a security |
| 1749 | risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module |
| 1750 | to provide digest authentication. |
| 1751 | |
| 1752 | An authentication key is a string which can be thought of as a password: once a |
| 1753 | connection is established both ends will demand proof that the other knows the |
| 1754 | authentication key. (Demonstrating that both ends are using the same key does |
| 1755 | **not** involve sending the key over the connection.) |
| 1756 | |
| 1757 | If authentication is requested but do authentication key is specified then the |
| 1758 | return value of ``current_process().get_auth_key`` is used (see |
| 1759 | :class:`Process`). This value will automatically inherited by any |
| 1760 | :class:`Process` object that the current process creates. This means that (by |
| 1761 | default) all processes of a multi-process program will share a single |
| 1762 | authentication key which can be used when setting up connections between the |
| 1763 | themselves. |
| 1764 | |
| 1765 | Suitable authentication keys can also be generated by using :func:`os.urandom`. |
| 1766 | |
| 1767 | |
| 1768 | Logging |
| 1769 | ~~~~~~~ |
| 1770 | |
| 1771 | Some support for logging is available. Note, however, that the :mod:`logging` |
| 1772 | package does not use process shared locks so it is possible (depending on the |
| 1773 | handler type) for messages from different processes to get mixed up. |
| 1774 | |
| 1775 | .. currentmodule:: multiprocessing |
| 1776 | .. function:: get_logger() |
| 1777 | |
| 1778 | Returns the logger used by :mod:`multiprocessing`. If necessary, a new one |
| 1779 | will be created. |
| 1780 | |
| 1781 | When first created the logger has level :data:`logging.NOTSET` and has a |
| 1782 | handler which sends output to :data:`sys.stderr` using format |
| 1783 | ``'[%(levelname)s/%(processName)s] %(message)s'``. (The logger allows use of |
| 1784 | the non-standard ``'%(processName)s'`` format.) Message sent to this logger |
| 1785 | will not by default propogate to the root logger. |
| 1786 | |
| 1787 | Note that on Windows child processes will only inherit the level of the |
| 1788 | parent process's logger -- any other customization of the logger will not be |
| 1789 | inherited. |
| 1790 | |
| 1791 | Below is an example session with logging turned on:: |
| 1792 | |
| 1793 | >>> import processing, logging |
| 1794 | >>> logger = processing.getLogger() |
| 1795 | >>> logger.setLevel(logging.INFO) |
| 1796 | >>> logger.warning('doomed') |
| 1797 | [WARNING/MainProcess] doomed |
| 1798 | >>> m = processing.Manager() |
| 1799 | [INFO/SyncManager-1] child process calling self.run() |
| 1800 | [INFO/SyncManager-1] manager bound to '\\\\.\\pipe\\pyc-2776-0-lj0tfa' |
| 1801 | >>> del m |
| 1802 | [INFO/MainProcess] sending shutdown message to manager |
| 1803 | [INFO/SyncManager-1] manager exiting with exitcode 0 |
| 1804 | |
| 1805 | |
| 1806 | The :mod:`multiprocessing.dummy` module |
| 1807 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1808 | |
| 1809 | .. module:: multiprocessing.dummy |
| 1810 | :synopsis: Dumb wrapper around threading. |
| 1811 | |
| 1812 | :mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is |
| 1813 | no more than a wrapper around the `threading` module. |
| 1814 | |
| 1815 | |
| 1816 | .. _multiprocessing-programming: |
| 1817 | |
| 1818 | Programming guidelines |
| 1819 | ---------------------- |
| 1820 | |
| 1821 | There are certain guidelines and idioms which should be adhered to when using |
| 1822 | :mod:`multiprocessing`. |
| 1823 | |
| 1824 | |
| 1825 | All platforms |
| 1826 | ~~~~~~~~~~~~~ |
| 1827 | |
| 1828 | Avoid shared state |
| 1829 | |
| 1830 | As far as possible one should try to avoid shifting large amounts of data |
| 1831 | between processes. |
| 1832 | |
| 1833 | It is probably best to stick to using queues or pipes for communication |
| 1834 | between processes rather than using the lower level synchronization |
| 1835 | primitives from the :mod:`threading` module. |
| 1836 | |
| 1837 | Picklability |
| 1838 | |
| 1839 | Ensure that the arguments to the methods of proxies are picklable. |
| 1840 | |
| 1841 | Thread safety of proxies |
| 1842 | |
| 1843 | Do not use a proxy object from more than one thread unless you protect it |
| 1844 | with a lock. |
| 1845 | |
| 1846 | (There is never a problem with different processes using the *same* proxy.) |
| 1847 | |
| 1848 | Joining zombie processes |
| 1849 | |
| 1850 | On Unix when a process finishes but has not been joined it becomes a zombie. |
| 1851 | There should never be very many because each time a new process starts (or |
| 1852 | :func:`active_children` is called) all completed processes which have not |
| 1853 | yet been joined will be joined. Also calling a finished process's |
| 1854 | :meth:`Process.is_alive` will join the process. Even so it is probably good |
| 1855 | practice to explicitly join all the processes that you start. |
| 1856 | |
| 1857 | Better to inherit than pickle/unpickle |
| 1858 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 1859 | On Windows many types from :mod:`multiprocessing` need to be picklable so |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 1860 | that child processes can use them. However, one should generally avoid |
| 1861 | sending shared objects to other processes using pipes or queues. Instead |
| 1862 | you should arrange the program so that a process which need access to a |
| 1863 | shared resource created elsewhere can inherit it from an ancestor process. |
| 1864 | |
| 1865 | Avoid terminating processes |
| 1866 | |
| 1867 | Using the :meth:`Process.terminate` method to stop a process is liable to |
| 1868 | cause any shared resources (such as locks, semaphores, pipes and queues) |
| 1869 | currently being used by the process to become broken or unavailable to other |
| 1870 | processes. |
| 1871 | |
| 1872 | Therefore it is probably best to only consider using |
| 1873 | :meth:`Process.terminate()` on processes which never use any shared |
| 1874 | resources. |
| 1875 | |
| 1876 | Joining processes that use queues |
| 1877 | |
| 1878 | Bear in mind that a process that has put items in a queue will wait before |
| 1879 | terminating until all the buffered items are fed by the "feeder" thread to |
| 1880 | the underlying pipe. (The child process can call the |
| 1881 | :meth:`Queue.cancel_join` method of the queue to avoid this behaviour.) |
| 1882 | |
| 1883 | This means that whenever you use a queue you need to make sure that all |
| 1884 | items which have been put on the queue will eventually be removed before the |
| 1885 | process is joined. Otherwise you cannot be sure that processes which have |
| 1886 | put items on the queue will terminate. Remember also that non-daemonic |
| 1887 | processes will be automatically be joined. |
| 1888 | |
| 1889 | An example which will deadlock is the following:: |
| 1890 | |
| 1891 | from multiprocessing import Process, Queue |
| 1892 | |
| 1893 | def f(q): |
| 1894 | q.put('X' * 1000000) |
| 1895 | |
| 1896 | if __name__ == '__main__': |
| 1897 | queue = Queue() |
| 1898 | p = Process(target=f, args=(queue,)) |
| 1899 | p.start() |
| 1900 | p.join() # this deadlocks |
| 1901 | obj = queue.get() |
| 1902 | |
| 1903 | A fix here would be to swap the last two lines round (or simply remove the |
| 1904 | ``p.join()`` line). |
| 1905 | |
Andrew M. Kuchling | be504f1 | 2008-06-19 19:48:42 +0000 | [diff] [blame] | 1906 | Explicitly pass resources to child processes |
Benjamin Peterson | 190d56e | 2008-06-11 02:40:25 +0000 | [diff] [blame] | 1907 | |
| 1908 | On Unix a child process can make use of a shared resource created in a |
| 1909 | parent process using a global resource. However, it is better to pass the |
| 1910 | object as an argument to the constructor for the child process. |
| 1911 | |
| 1912 | Apart from making the code (potentially) compatible with Windows this also |
| 1913 | ensures that as long as the child process is still alive the object will not |
| 1914 | be garbage collected in the parent process. This might be important if some |
| 1915 | resource is freed when the object is garbage collected in the parent |
| 1916 | process. |
| 1917 | |
| 1918 | So for instance :: |
| 1919 | |
| 1920 | from multiprocessing import Process, Lock |
| 1921 | |
| 1922 | def f(): |
| 1923 | ... do something using "lock" ... |
| 1924 | |
| 1925 | if __name__ == '__main__': |
| 1926 | lock = Lock() |
| 1927 | for i in range(10): |
| 1928 | Process(target=f).start() |
| 1929 | |
| 1930 | should be rewritten as :: |
| 1931 | |
| 1932 | from multiprocessing import Process, Lock |
| 1933 | |
| 1934 | def f(l): |
| 1935 | ... do something using "l" ... |
| 1936 | |
| 1937 | if __name__ == '__main__': |
| 1938 | lock = Lock() |
| 1939 | for i in range(10): |
| 1940 | Process(target=f, args=(lock,)).start() |
| 1941 | |
| 1942 | |
| 1943 | Windows |
| 1944 | ~~~~~~~ |
| 1945 | |
| 1946 | Since Windows lacks :func:`os.fork` it has a few extra restrictions: |
| 1947 | |
| 1948 | More picklability |
| 1949 | |
| 1950 | Ensure that all arguments to :meth:`Process.__init__` are picklable. This |
| 1951 | means, in particular, that bound or unbound methods cannot be used directly |
| 1952 | as the ``target`` argument on Windows --- just define a function and use |
| 1953 | that instead. |
| 1954 | |
| 1955 | Also, if you subclass :class:`Process` then make sure that instances will be |
| 1956 | picklable when the :meth:`Process.start` method is called. |
| 1957 | |
| 1958 | Global variables |
| 1959 | |
| 1960 | Bear in mind that if code run in a child process tries to access a global |
| 1961 | variable, then the value it sees (if any) may not be the same as the value |
| 1962 | in the parent process at the time that :meth:`Process.start` was called. |
| 1963 | |
| 1964 | However, global variables which are just module level constants cause no |
| 1965 | problems. |
| 1966 | |
| 1967 | Safe importing of main module |
| 1968 | |
| 1969 | Make sure that the main module can be safely imported by a new Python |
| 1970 | interpreter without causing unintended side effects (such a starting a new |
| 1971 | process). |
| 1972 | |
| 1973 | For example, under Windows running the following module would fail with a |
| 1974 | :exc:`RuntimeError`:: |
| 1975 | |
| 1976 | from multiprocessing import Process |
| 1977 | |
| 1978 | def foo(): |
| 1979 | print 'hello' |
| 1980 | |
| 1981 | p = Process(target=foo) |
| 1982 | p.start() |
| 1983 | |
| 1984 | Instead one should protect the "entry point" of the program by using ``if |
| 1985 | __name__ == '__main__':`` as follows:: |
| 1986 | |
| 1987 | from multiprocessing import Process, freeze_support |
| 1988 | |
| 1989 | def foo(): |
| 1990 | print 'hello' |
| 1991 | |
| 1992 | if __name__ == '__main__': |
| 1993 | freeze_support() |
| 1994 | p = Process(target=foo) |
| 1995 | p.start() |
| 1996 | |
| 1997 | (The :func:`freeze_support()` line can be omitted if the program will be run |
| 1998 | normally instead of frozen.) |
| 1999 | |
| 2000 | This allows the newly spawned Python interpreter to safely import the module |
| 2001 | and then run the module's ``foo()`` function. |
| 2002 | |
| 2003 | Similar restrictions apply if a pool or manager is created in the main |
| 2004 | module. |
| 2005 | |
| 2006 | |
| 2007 | .. _multiprocessing-examples: |
| 2008 | |
| 2009 | Examples |
| 2010 | -------- |
| 2011 | |
| 2012 | Demonstration of how to create and use customized managers and proxies: |
| 2013 | |
| 2014 | .. literalinclude:: ../includes/mp_newtype.py |
| 2015 | |
| 2016 | |
| 2017 | Using :class:`Pool`: |
| 2018 | |
| 2019 | .. literalinclude:: ../includes/mp_pool.py |
| 2020 | |
| 2021 | |
| 2022 | Synchronization types like locks, conditions and queues: |
| 2023 | |
| 2024 | .. literalinclude:: ../includes/mp_synchronize.py |
| 2025 | |
| 2026 | |
| 2027 | An showing how to use queues to feed tasks to a collection of worker process and |
| 2028 | collect the results: |
| 2029 | |
| 2030 | .. literalinclude:: ../includes/mp_workers.py |
| 2031 | |
| 2032 | |
| 2033 | An example of how a pool of worker processes can each run a |
| 2034 | :class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening |
| 2035 | socket. |
| 2036 | |
| 2037 | .. literalinclude:: ../includes/mp_webserver.py |
| 2038 | |
| 2039 | |
| 2040 | Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`: |
| 2041 | |
| 2042 | .. literalinclude:: ../includes/mp_benchmarks.py |
| 2043 | |
| 2044 | An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process` |
| 2045 | and others to build a system which can distribute processes and work via a |
| 2046 | distributed queue to a "cluster" of machines on a network, accessible via SSH. |
| 2047 | You will need to have private key authentication for all hosts configured for |
| 2048 | this to work. |
| 2049 | |
| 2050 | .. literalinclude:: ../includes/mp_distributing.py |