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