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