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