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