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