blob: 77cb877c92d32d38c4dc75625e69abe927ac1b96 [file] [log] [blame]
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001:mod:`multiprocessing` --- Process-based "threading" interface
2==============================================================
3
4.. module:: multiprocessing
5 :synopsis: Process-based "threading" interface.
6
7.. versionadded:: 2.6
8
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00009
Benjamin Peterson190d56e2008-06-11 02:40:25 +000010Introduction
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +000011----------------------
Benjamin Peterson190d56e2008-06-11 02:40:25 +000012
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000013:mod:`multiprocessing` is a package that supports spawning processes using an
14API similar to the :mod:`threading` module. The :mod:`multiprocessing` package
15offers both local and remote concurrency, effectively side-stepping the
16:term:`Global Interpreter Lock` by using subprocesses instead of threads. Due
17to this, the :mod:`multiprocessing` module allows the programmer to fully
18leverage multiple processors on a given machine. It runs on both Unix and
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +000019Windows.
Benjamin Peterson190d56e2008-06-11 02:40:25 +000020
Antoine Pitroua8efb6b2015-01-11 15:09:27 +010021The :mod:`multiprocessing` module also introduces APIs which do not have
22analogs in the :mod:`threading` module. A prime example of this is the
23:class:`Pool` object which offers a convenient means of parallelizing the
24execution of a function across multiple input values, distributing the
25input data across processes (data parallelism). The following example
26demonstrates the common practice of defining such functions in a module so
27that child processes can successfully import that module. This basic example
28of data parallelism using :class:`Pool`, ::
Jesse Noller37040cd2008-09-30 00:15:45 +000029
Antoine Pitroua8efb6b2015-01-11 15:09:27 +010030 from multiprocessing import Pool
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000031
Antoine Pitroua8efb6b2015-01-11 15:09:27 +010032 def f(x):
33 return x*x
Jesse Nollera280fd72008-11-28 18:22:54 +000034
Antoine Pitroua8efb6b2015-01-11 15:09:27 +010035 if __name__ == '__main__':
36 p = Pool(5)
37 print(p.map(f, [1, 2, 3]))
Jesse Nollera280fd72008-11-28 18:22:54 +000038
Antoine Pitroua8efb6b2015-01-11 15:09:27 +010039will print to standard output ::
Jesse Nollera280fd72008-11-28 18:22:54 +000040
Antoine Pitroua8efb6b2015-01-11 15:09:27 +010041 [1, 4, 9]
R. David Murray636b23a2009-04-28 16:08:18 +000042
Jesse Nollera280fd72008-11-28 18:22:54 +000043
Benjamin Peterson190d56e2008-06-11 02:40:25 +000044The :class:`Process` class
45~~~~~~~~~~~~~~~~~~~~~~~~~~
46
47In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000048object and then calling its :meth:`~Process.start` method. :class:`Process`
Benjamin Peterson190d56e2008-06-11 02:40:25 +000049follows the API of :class:`threading.Thread`. A trivial example of a
50multiprocess program is ::
51
Jesse Nollera280fd72008-11-28 18:22:54 +000052 from multiprocessing import Process
Benjamin Peterson190d56e2008-06-11 02:40:25 +000053
Jesse Nollera280fd72008-11-28 18:22:54 +000054 def f(name):
55 print 'hello', name
Benjamin Peterson190d56e2008-06-11 02:40:25 +000056
Jesse Nollera280fd72008-11-28 18:22:54 +000057 if __name__ == '__main__':
58 p = Process(target=f, args=('bob',))
59 p.start()
60 p.join()
Benjamin Peterson190d56e2008-06-11 02:40:25 +000061
Jesse Nollera280fd72008-11-28 18:22:54 +000062To show the individual process IDs involved, here is an expanded example::
63
64 from multiprocessing import Process
65 import os
66
67 def info(title):
68 print title
69 print 'module name:', __name__
Georg Brandle683ef52012-07-01 09:47:54 +020070 if hasattr(os, 'getppid'): # only available on Unix
71 print 'parent process:', os.getppid()
Jesse Nollera280fd72008-11-28 18:22:54 +000072 print 'process id:', os.getpid()
Georg Brandlc62ef8b2009-01-03 20:55:06 +000073
Jesse Nollera280fd72008-11-28 18:22:54 +000074 def f(name):
75 info('function f')
76 print 'hello', name
Georg Brandlc62ef8b2009-01-03 20:55:06 +000077
Jesse Nollera280fd72008-11-28 18:22:54 +000078 if __name__ == '__main__':
79 info('main line')
80 p = Process(target=f, args=('bob',))
81 p.start()
82 p.join()
Benjamin Peterson190d56e2008-06-11 02:40:25 +000083
84For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is
85necessary, see :ref:`multiprocessing-programming`.
86
87
Benjamin Peterson190d56e2008-06-11 02:40:25 +000088Exchanging objects between processes
89~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
90
91:mod:`multiprocessing` supports two types of communication channel between
92processes:
93
94**Queues**
95
Sandro Tosi8b48c662012-02-25 19:35:16 +010096 The :class:`~multiprocessing.Queue` class is a near clone of :class:`Queue.Queue`. For
Benjamin Peterson190d56e2008-06-11 02:40:25 +000097 example::
98
99 from multiprocessing import Process, Queue
100
101 def f(q):
102 q.put([42, None, 'hello'])
103
Georg Brandledd7d952009-01-03 14:29:53 +0000104 if __name__ == '__main__':
105 q = Queue()
106 p = Process(target=f, args=(q,))
107 p.start()
108 print q.get() # prints "[42, None, 'hello']"
109 p.join()
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000110
111 Queues are thread and process safe.
112
113**Pipes**
114
115 The :func:`Pipe` function returns a pair of connection objects connected by a
116 pipe which by default is duplex (two-way). For example::
117
118 from multiprocessing import Process, Pipe
119
120 def f(conn):
121 conn.send([42, None, 'hello'])
122 conn.close()
123
124 if __name__ == '__main__':
125 parent_conn, child_conn = Pipe()
126 p = Process(target=f, args=(child_conn,))
127 p.start()
128 print parent_conn.recv() # prints "[42, None, 'hello']"
129 p.join()
130
131 The two connection objects returned by :func:`Pipe` represent the two ends of
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000132 the pipe. Each connection object has :meth:`~Connection.send` and
133 :meth:`~Connection.recv` methods (among others). Note that data in a pipe
134 may become corrupted if two processes (or threads) try to read from or write
135 to the *same* end of the pipe at the same time. Of course there is no risk
136 of corruption from processes using different ends of the pipe at the same
137 time.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000138
139
140Synchronization between processes
141~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142
143:mod:`multiprocessing` contains equivalents of all the synchronization
144primitives from :mod:`threading`. For instance one can use a lock to ensure
145that only one process prints to standard output at a time::
146
147 from multiprocessing import Process, Lock
148
149 def f(l, i):
150 l.acquire()
151 print 'hello world', i
152 l.release()
153
154 if __name__ == '__main__':
155 lock = Lock()
156
157 for num in range(10):
158 Process(target=f, args=(lock, num)).start()
159
160Without using the lock output from the different processes is liable to get all
161mixed up.
162
Antoine Pitroua8efb6b2015-01-11 15:09:27 +0100163.. warning::
164
165 Some of this package's functionality requires a functioning shared semaphore
166 implementation on the host operating system. Without one, the
167 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
168 import it will result in an :exc:`ImportError`. See
169 :issue:`3770` for additional information.
170
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000171
172Sharing state between processes
173~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174
175As mentioned above, when doing concurrent programming it is usually best to
176avoid using shared state as far as possible. This is particularly true when
177using multiple processes.
178
179However, if you really do need to use some shared data then
180:mod:`multiprocessing` provides a couple of ways of doing so.
181
182**Shared memory**
183
184 Data can be stored in a shared memory map using :class:`Value` or
185 :class:`Array`. For example, the following code ::
186
187 from multiprocessing import Process, Value, Array
188
189 def f(n, a):
190 n.value = 3.1415927
191 for i in range(len(a)):
192 a[i] = -a[i]
193
194 if __name__ == '__main__':
195 num = Value('d', 0.0)
196 arr = Array('i', range(10))
197
198 p = Process(target=f, args=(num, arr))
199 p.start()
200 p.join()
201
202 print num.value
203 print arr[:]
204
205 will print ::
206
207 3.1415927
208 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
209
210 The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
211 typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
Benjamin Peterson90f36732008-07-12 20:16:19 +0000212 double precision float and ``'i'`` indicates a signed integer. These shared
Georg Brandl837fbb02010-11-26 07:58:55 +0000213 objects will be process and thread-safe.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000214
215 For more flexibility in using shared memory one can use the
216 :mod:`multiprocessing.sharedctypes` module which supports the creation of
217 arbitrary ctypes objects allocated from shared memory.
218
219**Server process**
220
221 A manager object returned by :func:`Manager` controls a server process which
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000222 holds Python objects and allows other processes to manipulate them using
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000223 proxies.
224
225 A manager returned by :func:`Manager` will support types :class:`list`,
226 :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`,
227 :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
Sandro Tosi8b48c662012-02-25 19:35:16 +0100228 :class:`Event`, :class:`~multiprocessing.Queue`, :class:`Value` and :class:`Array`. For
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000229 example, ::
230
231 from multiprocessing import Process, Manager
232
233 def f(d, l):
234 d[1] = '1'
235 d['2'] = 2
236 d[0.25] = None
237 l.reverse()
238
239 if __name__ == '__main__':
240 manager = Manager()
241
242 d = manager.dict()
243 l = manager.list(range(10))
244
245 p = Process(target=f, args=(d, l))
246 p.start()
247 p.join()
248
249 print d
250 print l
251
252 will print ::
253
254 {0.25: None, 1: '1', '2': 2}
255 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
256
257 Server process managers are more flexible than using shared memory objects
258 because they can be made to support arbitrary object types. Also, a single
259 manager can be shared by processes on different computers over a network.
260 They are, however, slower than using shared memory.
261
262
263Using a pool of workers
264~~~~~~~~~~~~~~~~~~~~~~~
265
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000266The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000267processes. It has methods which allows tasks to be offloaded to the worker
268processes in a few different ways.
269
270For example::
271
272 from multiprocessing import Pool
273
274 def f(x):
275 return x*x
276
277 if __name__ == '__main__':
278 pool = Pool(processes=4) # start 4 worker processes
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200279 result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000280 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
281 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
282
Richard Oudkerk49032532013-07-02 12:31:50 +0100283Note that the methods of a pool should only ever be used by the
284process which created it.
285
Antoine Pitroua8efb6b2015-01-11 15:09:27 +0100286.. note::
287
288 Functionality within this package requires that the ``__main__`` module be
289 importable by the children. This is covered in :ref:`multiprocessing-programming`
290 however it is worth pointing out here. This means that some examples, such
291 as the :class:`Pool` examples will not work in the interactive interpreter.
292 For example::
293
294 >>> from multiprocessing import Pool
295 >>> p = Pool(5)
296 >>> def f(x):
297 ... return x*x
298 ...
299 >>> p.map(f, [1,2,3])
300 Process PoolWorker-1:
301 Process PoolWorker-2:
302 Process PoolWorker-3:
303 Traceback (most recent call last):
304 Traceback (most recent call last):
305 Traceback (most recent call last):
306 AttributeError: 'module' object has no attribute 'f'
307 AttributeError: 'module' object has no attribute 'f'
308 AttributeError: 'module' object has no attribute 'f'
309
310 (If you try this it will actually output three full tracebacks
311 interleaved in a semi-random fashion, and then you may have to
312 stop the master process somehow.)
313
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000314
315Reference
316---------
317
318The :mod:`multiprocessing` package mostly replicates the API of the
319:mod:`threading` module.
320
321
322:class:`Process` and exceptions
323~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
324
Ezio Melottied3f5902012-09-14 06:48:32 +0300325.. class:: Process(group=None, target=None, name=None, args=(), kwargs={})
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000326
327 Process objects represent activity that is run in a separate process. The
328 :class:`Process` class has equivalents of all the methods of
329 :class:`threading.Thread`.
330
331 The constructor should always be called with keyword arguments. *group*
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000332 should always be ``None``; it exists solely for compatibility with
Benjamin Peterson73641d72008-08-20 14:07:59 +0000333 :class:`threading.Thread`. *target* is the callable object to be invoked by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000334 the :meth:`run()` method. It defaults to ``None``, meaning nothing is
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000335 called. *name* is the process name. By default, a unique name is constructed
336 of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\
337 :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
338 is determined by the *generation* of the process. *args* is the argument
339 tuple for the target invocation. *kwargs* is a dictionary of keyword
340 arguments for the target invocation. By default, no arguments are passed to
341 *target*.
342
343 If a subclass overrides the constructor, it must make sure it invokes the
344 base class constructor (:meth:`Process.__init__`) before doing anything else
345 to the process.
346
347 .. method:: run()
348
349 Method representing the process's activity.
350
351 You may override this method in a subclass. The standard :meth:`run`
352 method invokes the callable object passed to the object's constructor as
353 the target argument, if any, with sequential and keyword arguments taken
354 from the *args* and *kwargs* arguments, respectively.
355
356 .. method:: start()
357
358 Start the process's activity.
359
360 This must be called at most once per process object. It arranges for the
361 object's :meth:`run` method to be invoked in a separate process.
362
363 .. method:: join([timeout])
364
365 Block the calling thread until the process whose :meth:`join` method is
366 called terminates or until the optional timeout occurs.
367
368 If *timeout* is ``None`` then there is no timeout.
369
370 A process can be joined many times.
371
372 A process cannot join itself because this would cause a deadlock. It is
373 an error to attempt to join a process before it has been started.
374
Benjamin Peterson73641d72008-08-20 14:07:59 +0000375 .. attribute:: name
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000376
Benjamin Peterson73641d72008-08-20 14:07:59 +0000377 The process's name.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000378
379 The name is a string used for identification purposes only. It has no
380 semantics. Multiple processes may be given the same name. The initial
381 name is set by the constructor.
382
Jesse Nollera280fd72008-11-28 18:22:54 +0000383 .. method:: is_alive
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000384
385 Return whether the process is alive.
386
387 Roughly, a process object is alive from the moment the :meth:`start`
388 method returns until the child process terminates.
389
Benjamin Peterson73641d72008-08-20 14:07:59 +0000390 .. attribute:: daemon
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000391
Georg Brandl3bcb0ce2008-12-30 10:15:49 +0000392 The process's daemon flag, a Boolean value. This must be set before
Benjamin Peterson73641d72008-08-20 14:07:59 +0000393 :meth:`start` is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000394
395 The initial value is inherited from the creating process.
396
397 When a process exits, it attempts to terminate all of its daemonic child
398 processes.
399
400 Note that a daemonic process is not allowed to create child processes.
401 Otherwise a daemonic process would leave its children orphaned if it gets
Jesse Nollerd4792cd2009-06-29 18:20:34 +0000402 terminated when its parent process exits. Additionally, these are **not**
403 Unix daemons or services, they are normal processes that will be
Georg Brandl09302282010-10-06 09:32:48 +0000404 terminated (and not joined) if non-daemonic processes have exited.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000405
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300406 In addition to the :class:`threading.Thread` API, :class:`Process` objects
Brett Cannon971f1022008-08-24 23:15:19 +0000407 also support the following attributes and methods:
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000408
Benjamin Peterson73641d72008-08-20 14:07:59 +0000409 .. attribute:: pid
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000410
411 Return the process ID. Before the process is spawned, this will be
412 ``None``.
413
Benjamin Peterson73641d72008-08-20 14:07:59 +0000414 .. attribute:: exitcode
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000415
Benjamin Peterson73641d72008-08-20 14:07:59 +0000416 The child's exit code. This will be ``None`` if the process has not yet
417 terminated. A negative value *-N* indicates that the child was terminated
418 by signal *N*.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000419
Benjamin Peterson73641d72008-08-20 14:07:59 +0000420 .. attribute:: authkey
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000421
Benjamin Peterson73641d72008-08-20 14:07:59 +0000422 The process's authentication key (a byte string).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000423
424 When :mod:`multiprocessing` is initialized the main process is assigned a
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300425 random string using :func:`os.urandom`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000426
427 When a :class:`Process` object is created, it will inherit the
Benjamin Peterson73641d72008-08-20 14:07:59 +0000428 authentication key of its parent process, although this may be changed by
429 setting :attr:`authkey` to another byte string.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000430
431 See :ref:`multiprocessing-auth-keys`.
432
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000433 .. method:: terminate()
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000434
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000435 Terminate the process. On Unix this is done using the ``SIGTERM`` signal;
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100436 on Windows :c:func:`TerminateProcess` is used. Note that exit handlers and
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000437 finally clauses, etc., will not be executed.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000438
439 Note that descendant processes of the process will *not* be terminated --
440 they will simply become orphaned.
441
442 .. warning::
443
444 If this method is used when the associated process is using a pipe or
445 queue then the pipe or queue is liable to become corrupted and may
446 become unusable by other process. Similarly, if the process has
447 acquired a lock or semaphore etc. then terminating it is liable to
448 cause other processes to deadlock.
449
Richard Oudkerkacfbe222013-06-24 15:41:36 +0100450 Note that the :meth:`start`, :meth:`join`, :meth:`is_alive`,
451 :meth:`terminate` and :attr:`exitcode` methods should only be called by
452 the process that created the process object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000453
R. David Murray636b23a2009-04-28 16:08:18 +0000454 Example usage of some of the methods of :class:`Process`:
455
456 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000457
Georg Brandl19cc9442008-10-16 21:36:39 +0000458 >>> import multiprocessing, time, signal
459 >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000460 >>> print p, p.is_alive()
461 <Process(Process-1, initial)> False
462 >>> p.start()
463 >>> print p, p.is_alive()
464 <Process(Process-1, started)> True
465 >>> p.terminate()
R. David Murray636b23a2009-04-28 16:08:18 +0000466 >>> time.sleep(0.1)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000467 >>> print p, p.is_alive()
468 <Process(Process-1, stopped[SIGTERM])> False
Benjamin Peterson73641d72008-08-20 14:07:59 +0000469 >>> p.exitcode == -signal.SIGTERM
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000470 True
471
472
473.. exception:: BufferTooShort
474
475 Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
476 buffer object is too small for the message read.
477
478 If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
479 the message as a byte string.
480
481
482Pipes and Queues
483~~~~~~~~~~~~~~~~
484
485When using multiple processes, one generally uses message passing for
486communication between processes and avoids having to use any synchronization
487primitives like locks.
488
489For passing messages one can use :func:`Pipe` (for a connection between two
490processes) or a queue (which allows multiple producers and consumers).
491
Sandro Tosi8b48c662012-02-25 19:35:16 +0100492The :class:`~multiprocessing.Queue`, :class:`multiprocessing.queues.SimpleQueue` and :class:`JoinableQueue` types are multi-producer,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000493multi-consumer FIFO queues modelled on the :class:`Queue.Queue` class in the
Sandro Tosi8b48c662012-02-25 19:35:16 +0100494standard library. They differ in that :class:`~multiprocessing.Queue` lacks the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000495:meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join` methods introduced
496into Python 2.5's :class:`Queue.Queue` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000497
498If you use :class:`JoinableQueue` then you **must** call
499:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200500semaphore used to count the number of unfinished tasks may eventually overflow,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000501raising an exception.
502
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000503Note that one can also create a shared queue by using a manager object -- see
504:ref:`multiprocessing-managers`.
505
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000506.. note::
507
508 :mod:`multiprocessing` uses the usual :exc:`Queue.Empty` and
509 :exc:`Queue.Full` exceptions to signal a timeout. They are not available in
510 the :mod:`multiprocessing` namespace so you need to import them from
511 :mod:`Queue`.
512
Richard Oudkerk56e968c2013-06-24 14:45:24 +0100513.. note::
514
515 When an object is put on a queue, the object is pickled and a
516 background thread later flushes the pickled data to an underlying
517 pipe. This has some consequences which are a little surprising,
Richard Oudkerk2cc73e82013-06-24 18:11:21 +0100518 but should not cause any practical difficulties -- if they really
519 bother you then you can instead use a queue created with a
520 :ref:`manager <multiprocessing-managers>`.
Richard Oudkerk56e968c2013-06-24 14:45:24 +0100521
522 (1) After putting an object on an empty queue there may be an
Richard Oudkerk66e0a042013-06-24 20:38:22 +0100523 infinitesimal delay before the queue's :meth:`~Queue.empty`
Richard Oudkerk56e968c2013-06-24 14:45:24 +0100524 method returns :const:`False` and :meth:`~Queue.get_nowait` can
525 return without raising :exc:`Queue.Empty`.
526
527 (2) If multiple processes are enqueuing objects, it is possible for
528 the objects to be received at the other end out-of-order.
529 However, objects enqueued by the same process will always be in
530 the expected order with respect to each other.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000531
532.. warning::
533
534 If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
Sandro Tosi8b48c662012-02-25 19:35:16 +0100535 while it is trying to use a :class:`~multiprocessing.Queue`, then the data in the queue is
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200536 likely to become corrupted. This may cause any other process to get an
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000537 exception when it tries to use the queue later on.
538
539.. warning::
540
541 As mentioned above, if a child process has put items on a queue (and it has
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300542 not used :meth:`JoinableQueue.cancel_join_thread
543 <multiprocessing.Queue.cancel_join_thread>`), then that process will
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000544 not terminate until all buffered items have been flushed to the pipe.
545
546 This means that if you try joining that process you may get a deadlock unless
547 you are sure that all items which have been put on the queue have been
548 consumed. Similarly, if the child process is non-daemonic then the parent
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000549 process may hang on exit when it tries to join all its non-daemonic children.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000550
551 Note that a queue created using a manager does not have this issue. See
552 :ref:`multiprocessing-programming`.
553
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000554For an example of the usage of queues for interprocess communication see
555:ref:`multiprocessing-examples`.
556
557
558.. function:: Pipe([duplex])
559
560 Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing
561 the ends of a pipe.
562
563 If *duplex* is ``True`` (the default) then the pipe is bidirectional. If
564 *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
565 used for receiving messages and ``conn2`` can only be used for sending
566 messages.
567
568
569.. class:: Queue([maxsize])
570
571 Returns a process shared queue implemented using a pipe and a few
572 locks/semaphores. When a process first puts an item on the queue a feeder
573 thread is started which transfers objects from a buffer into the pipe.
574
575 The usual :exc:`Queue.Empty` and :exc:`Queue.Full` exceptions from the
576 standard library's :mod:`Queue` module are raised to signal timeouts.
577
Sandro Tosi8b48c662012-02-25 19:35:16 +0100578 :class:`~multiprocessing.Queue` implements all the methods of :class:`Queue.Queue` except for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000579 :meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000580
581 .. method:: qsize()
582
583 Return the approximate size of the queue. Because of
584 multithreading/multiprocessing semantics, this number is not reliable.
585
586 Note that this may raise :exc:`NotImplementedError` on Unix platforms like
Georg Brandl9af94982008-09-13 17:41:16 +0000587 Mac OS X where ``sem_getvalue()`` is not implemented.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000588
589 .. method:: empty()
590
591 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
592 multithreading/multiprocessing semantics, this is not reliable.
593
594 .. method:: full()
595
596 Return ``True`` if the queue is full, ``False`` otherwise. Because of
597 multithreading/multiprocessing semantics, this is not reliable.
598
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800599 .. method:: put(obj[, block[, timeout]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000600
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800601 Put obj into the queue. If the optional argument *block* is ``True``
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000602 (the default) and *timeout* is ``None`` (the default), block if necessary until
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000603 a free slot is available. If *timeout* is a positive number, it blocks at
604 most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
605 free slot was available within that time. Otherwise (*block* is
606 ``False``), put an item on the queue if a free slot is immediately
607 available, else raise the :exc:`Queue.Full` exception (*timeout* is
608 ignored in that case).
609
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800610 .. method:: put_nowait(obj)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000611
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800612 Equivalent to ``put(obj, False)``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000613
614 .. method:: get([block[, timeout]])
615
616 Remove and return an item from the queue. If optional args *block* is
617 ``True`` (the default) and *timeout* is ``None`` (the default), block if
618 necessary until an item is available. If *timeout* is a positive number,
619 it blocks at most *timeout* seconds and raises the :exc:`Queue.Empty`
620 exception if no item was available within that time. Otherwise (block is
621 ``False``), return an item if one is immediately available, else raise the
622 :exc:`Queue.Empty` exception (*timeout* is ignored in that case).
623
624 .. method:: get_nowait()
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000625
626 Equivalent to ``get(False)``.
627
Sandro Tosi8b48c662012-02-25 19:35:16 +0100628 :class:`~multiprocessing.Queue` has a few additional methods not found in
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000629 :class:`Queue.Queue`. These methods are usually unnecessary for most
630 code:
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000631
632 .. method:: close()
633
634 Indicate that no more data will be put on this queue by the current
635 process. The background thread will quit once it has flushed all buffered
636 data to the pipe. This is called automatically when the queue is garbage
637 collected.
638
639 .. method:: join_thread()
640
641 Join the background thread. This can only be used after :meth:`close` has
642 been called. It blocks until the background thread exits, ensuring that
643 all data in the buffer has been flushed to the pipe.
644
645 By default if a process is not the creator of the queue then on exit it
646 will attempt to join the queue's background thread. The process can call
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000647 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000648
649 .. method:: cancel_join_thread()
650
651 Prevent :meth:`join_thread` from blocking. In particular, this prevents
652 the background thread from being joined automatically when the process
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000653 exits -- see :meth:`join_thread`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000654
Richard Oudkerk4bc130c2013-07-02 12:58:21 +0100655 A better name for this method might be
656 ``allow_exit_without_flush()``. It is likely to cause enqueued
657 data to lost, and you almost certainly will not need to use it.
658 It is really only there if you need the current process to exit
659 immediately without waiting to flush enqueued data to the
660 underlying pipe, and you don't care about lost data.
661
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000662
Sandro Tosic0b11722012-02-15 22:39:52 +0100663.. class:: multiprocessing.queues.SimpleQueue()
664
Sandro Tosi8b48c662012-02-25 19:35:16 +0100665 It is a simplified :class:`~multiprocessing.Queue` type, very close to a locked :class:`Pipe`.
Sandro Tosic0b11722012-02-15 22:39:52 +0100666
667 .. method:: empty()
668
669 Return ``True`` if the queue is empty, ``False`` otherwise.
670
671 .. method:: get()
672
673 Remove and return an item from the queue.
674
675 .. method:: put(item)
676
677 Put *item* into the queue.
678
679
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000680.. class:: JoinableQueue([maxsize])
681
Sandro Tosi8b48c662012-02-25 19:35:16 +0100682 :class:`JoinableQueue`, a :class:`~multiprocessing.Queue` subclass, is a queue which
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000683 additionally has :meth:`task_done` and :meth:`join` methods.
684
685 .. method:: task_done()
686
687 Indicate that a formerly enqueued task is complete. Used by queue consumer
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000688 threads. For each :meth:`~Queue.get` used to fetch a task, a subsequent
689 call to :meth:`task_done` tells the queue that the processing on the task
690 is complete.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000691
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300692 If a :meth:`~Queue.Queue.join` is currently blocking, it will resume when all
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000693 items have been processed (meaning that a :meth:`task_done` call was
694 received for every item that had been :meth:`~Queue.put` into the queue).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000695
696 Raises a :exc:`ValueError` if called more times than there were items
697 placed in the queue.
698
699
700 .. method:: join()
701
702 Block until all items in the queue have been gotten and processed.
703
704 The count of unfinished tasks goes up whenever an item is added to the
705 queue. The count goes down whenever a consumer thread calls
706 :meth:`task_done` to indicate that the item was retrieved and all work on
707 it is complete. When the count of unfinished tasks drops to zero,
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300708 :meth:`~Queue.Queue.join` unblocks.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000709
710
711Miscellaneous
712~~~~~~~~~~~~~
713
714.. function:: active_children()
715
716 Return list of all live children of the current process.
717
Zachary Ware06b74a72014-10-03 10:55:12 -0500718 Calling this has the side effect of "joining" any processes which have
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000719 already finished.
720
721.. function:: cpu_count()
722
723 Return the number of CPUs in the system. May raise
724 :exc:`NotImplementedError`.
725
726.. function:: current_process()
727
728 Return the :class:`Process` object corresponding to the current process.
729
730 An analogue of :func:`threading.current_thread`.
731
732.. function:: freeze_support()
733
734 Add support for when a program which uses :mod:`multiprocessing` has been
735 frozen to produce a Windows executable. (Has been tested with **py2exe**,
736 **PyInstaller** and **cx_Freeze**.)
737
738 One needs to call this function straight after the ``if __name__ ==
739 '__main__'`` line of the main module. For example::
740
741 from multiprocessing import Process, freeze_support
742
743 def f():
744 print 'hello world!'
745
746 if __name__ == '__main__':
747 freeze_support()
748 Process(target=f).start()
749
R. David Murray636b23a2009-04-28 16:08:18 +0000750 If the ``freeze_support()`` line is omitted then trying to run the frozen
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000751 executable will raise :exc:`RuntimeError`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000752
753 If the module is being run normally by the Python interpreter then
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000754 :func:`freeze_support` has no effect.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000755
756.. function:: set_executable()
757
Ezio Melotti062d2b52009-12-19 22:41:49 +0000758 Sets the path of the Python interpreter to use when starting a child process.
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000759 (By default :data:`sys.executable` is used). Embedders will probably need to
760 do some thing like ::
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000761
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200762 set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000763
R. David Murray636b23a2009-04-28 16:08:18 +0000764 before they can create child processes. (Windows only)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000765
766
767.. note::
768
769 :mod:`multiprocessing` contains no analogues of
770 :func:`threading.active_count`, :func:`threading.enumerate`,
771 :func:`threading.settrace`, :func:`threading.setprofile`,
772 :class:`threading.Timer`, or :class:`threading.local`.
773
774
775Connection Objects
776~~~~~~~~~~~~~~~~~~
777
778Connection objects allow the sending and receiving of picklable objects or
779strings. They can be thought of as message oriented connected sockets.
780
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200781Connection objects are usually created using :func:`Pipe` -- see also
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000782:ref:`multiprocessing-listeners-clients`.
783
784.. class:: Connection
785
786 .. method:: send(obj)
787
788 Send an object to the other end of the connection which should be read
789 using :meth:`recv`.
790
Jesse Noller5053fbb2009-04-02 04:22:09 +0000791 The object must be picklable. Very large pickles (approximately 32 MB+,
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200792 though it depends on the OS) may raise a :exc:`ValueError` exception.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000793
794 .. method:: recv()
795
796 Return an object sent from the other end of the connection using
Sandro Tosif788cf72012-01-07 17:56:43 +0100797 :meth:`send`. Blocks until there its something to receive. Raises
798 :exc:`EOFError` if there is nothing left to receive
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000799 and the other end was closed.
800
801 .. method:: fileno()
802
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200803 Return the file descriptor or handle used by the connection.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000804
805 .. method:: close()
806
807 Close the connection.
808
809 This is called automatically when the connection is garbage collected.
810
811 .. method:: poll([timeout])
812
813 Return whether there is any data available to be read.
814
815 If *timeout* is not specified then it will return immediately. If
816 *timeout* is a number then this specifies the maximum time in seconds to
817 block. If *timeout* is ``None`` then an infinite timeout is used.
818
819 .. method:: send_bytes(buffer[, offset[, size]])
820
821 Send byte data from an object supporting the buffer interface as a
822 complete message.
823
824 If *offset* is given then data is read from that position in *buffer*. If
Jesse Noller5053fbb2009-04-02 04:22:09 +0000825 *size* is given then that many bytes will be read from buffer. Very large
826 buffers (approximately 32 MB+, though it depends on the OS) may raise a
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200827 :exc:`ValueError` exception
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000828
829 .. method:: recv_bytes([maxlength])
830
831 Return a complete message of byte data sent from the other end of the
Sandro Tosif788cf72012-01-07 17:56:43 +0100832 connection as a string. Blocks until there is something to receive.
833 Raises :exc:`EOFError` if there is nothing left
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000834 to receive and the other end has closed.
835
836 If *maxlength* is specified and the message is longer than *maxlength*
837 then :exc:`IOError` is raised and the connection will no longer be
838 readable.
839
840 .. method:: recv_bytes_into(buffer[, offset])
841
842 Read into *buffer* a complete message of byte data sent from the other end
Sandro Tosif788cf72012-01-07 17:56:43 +0100843 of the connection and return the number of bytes in the message. Blocks
844 until there is something to receive. Raises
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000845 :exc:`EOFError` if there is nothing left to receive and the other end was
846 closed.
847
848 *buffer* must be an object satisfying the writable buffer interface. If
849 *offset* is given then the message will be written into the buffer from
R. David Murray636b23a2009-04-28 16:08:18 +0000850 that position. Offset must be a non-negative integer less than the
851 length of *buffer* (in bytes).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000852
853 If the buffer is too short then a :exc:`BufferTooShort` exception is
854 raised and the complete message is available as ``e.args[0]`` where ``e``
855 is the exception instance.
856
857
858For example:
859
R. David Murray636b23a2009-04-28 16:08:18 +0000860.. doctest::
861
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000862 >>> from multiprocessing import Pipe
863 >>> a, b = Pipe()
864 >>> a.send([1, 'hello', None])
865 >>> b.recv()
866 [1, 'hello', None]
867 >>> b.send_bytes('thank you')
868 >>> a.recv_bytes()
869 'thank you'
870 >>> import array
871 >>> arr1 = array.array('i', range(5))
872 >>> arr2 = array.array('i', [0] * 10)
873 >>> a.send_bytes(arr1)
874 >>> count = b.recv_bytes_into(arr2)
875 >>> assert count == len(arr1) * arr1.itemsize
876 >>> arr2
877 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
878
879
880.. warning::
881
882 The :meth:`Connection.recv` method automatically unpickles the data it
883 receives, which can be a security risk unless you can trust the process
884 which sent the message.
885
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000886 Therefore, unless the connection object was produced using :func:`Pipe` you
887 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
888 methods after performing some sort of authentication. See
889 :ref:`multiprocessing-auth-keys`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000890
891.. warning::
892
893 If a process is killed while it is trying to read or write to a pipe then
894 the data in the pipe is likely to become corrupted, because it may become
895 impossible to be sure where the message boundaries lie.
896
897
898Synchronization primitives
899~~~~~~~~~~~~~~~~~~~~~~~~~~
900
901Generally synchronization primitives are not as necessary in a multiprocess
Andrew M. Kuchling8ea605c2008-07-14 01:18:16 +0000902program as they are in a multithreaded program. See the documentation for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000903:mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000904
905Note that one can also create synchronization primitives by using a manager
906object -- see :ref:`multiprocessing-managers`.
907
908.. class:: BoundedSemaphore([value])
909
910 A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`.
911
Georg Brandl042d6a42010-05-21 21:47:05 +0000912 (On Mac OS X, this is indistinguishable from :class:`Semaphore` because
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000913 ``sem_getvalue()`` is not implemented on that platform).
914
915.. class:: Condition([lock])
916
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000917 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000918
919 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
920 object from :mod:`multiprocessing`.
921
922.. class:: Event()
923
924 A clone of :class:`threading.Event`.
Jesse Noller02cb0eb2009-04-01 03:45:50 +0000925 This method returns the state of the internal semaphore on exit, so it
926 will always return ``True`` except if a timeout is given and the operation
927 times out.
928
929 .. versionchanged:: 2.7
930 Previously, the method always returned ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000931
932.. class:: Lock()
933
934 A non-recursive lock object: a clone of :class:`threading.Lock`.
935
936.. class:: RLock()
937
938 A recursive lock object: a clone of :class:`threading.RLock`.
939
940.. class:: Semaphore([value])
941
Ross Lagerwalla3ed3f02011-03-14 10:43:36 +0200942 A semaphore object: a clone of :class:`threading.Semaphore`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000943
944.. note::
945
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000946 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000947 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
948 by the equivalents in :mod:`threading`. The signature is
949 ``acquire(block=True, timeout=None)`` with keyword parameters being
950 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
951 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
952 ignored.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000953
Georg Brandl042d6a42010-05-21 21:47:05 +0000954 On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
955 a timeout will emulate that function's behavior using a sleeping loop.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000956
957.. note::
958
959 If the SIGINT signal generated by Ctrl-C arrives while the main thread is
960 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
961 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
962 or :meth:`Condition.wait` then the call will be immediately interrupted and
963 :exc:`KeyboardInterrupt` will be raised.
964
965 This differs from the behaviour of :mod:`threading` where SIGINT will be
966 ignored while the equivalent blocking calls are in progress.
967
968
969Shared :mod:`ctypes` Objects
970~~~~~~~~~~~~~~~~~~~~~~~~~~~~
971
972It is possible to create shared objects using shared memory which can be
973inherited by child processes.
974
Jesse Noller6ab22152009-01-18 02:45:38 +0000975.. function:: Value(typecode_or_type, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000976
977 Return a :mod:`ctypes` object allocated from shared memory. By default the
978 return value is actually a synchronized wrapper for the object.
979
980 *typecode_or_type* determines the type of the returned object: it is either a
981 ctypes type or a one character typecode of the kind used by the :mod:`array`
982 module. *\*args* is passed on to the constructor for the type.
983
Richard Oudkerka69712c2013-11-17 17:00:38 +0000984 If *lock* is ``True`` (the default) then a new recursive lock
985 object is created to synchronize access to the value. If *lock* is
986 a :class:`Lock` or :class:`RLock` object then that will be used to
987 synchronize access to the value. If *lock* is ``False`` then
988 access to the returned object will not be automatically protected
989 by a lock, so it will not necessarily be "process-safe".
990
991 Operations like ``+=`` which involve a read and write are not
992 atomic. So if, for instance, you want to atomically increment a
993 shared value it is insufficient to just do ::
994
995 counter.value += 1
996
997 Assuming the associated lock is recursive (which it is by default)
998 you can instead do ::
999
1000 with counter.get_lock():
1001 counter.value += 1
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001002
1003 Note that *lock* is a keyword-only argument.
1004
1005.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
1006
1007 Return a ctypes array allocated from shared memory. By default the return
1008 value is actually a synchronized wrapper for the array.
1009
1010 *typecode_or_type* determines the type of the elements of the returned array:
1011 it is either a ctypes type or a one character typecode of the kind used by
1012 the :mod:`array` module. If *size_or_initializer* is an integer, then it
1013 determines the length of the array, and the array will be initially zeroed.
1014 Otherwise, *size_or_initializer* is a sequence which is used to initialize
1015 the array and whose length determines the length of the array.
1016
1017 If *lock* is ``True`` (the default) then a new lock object is created to
1018 synchronize access to the value. If *lock* is a :class:`Lock` or
1019 :class:`RLock` object then that will be used to synchronize access to the
1020 value. If *lock* is ``False`` then access to the returned object will not be
1021 automatically protected by a lock, so it will not necessarily be
1022 "process-safe".
1023
1024 Note that *lock* is a keyword only argument.
1025
Georg Brandlb053f992008-11-22 08:34:14 +00001026 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001027 attributes which allow one to use it to store and retrieve strings.
1028
1029
1030The :mod:`multiprocessing.sharedctypes` module
1031>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1032
1033.. module:: multiprocessing.sharedctypes
1034 :synopsis: Allocate ctypes objects from shared memory.
1035
1036The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
1037:mod:`ctypes` objects from shared memory which can be inherited by child
1038processes.
1039
1040.. note::
1041
Benjamin Peterson90f36732008-07-12 20:16:19 +00001042 Although it is possible to store a pointer in shared memory remember that
1043 this will refer to a location in the address space of a specific process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001044 However, the pointer is quite likely to be invalid in the context of a second
1045 process and trying to dereference the pointer from the second process may
1046 cause a crash.
1047
1048.. function:: RawArray(typecode_or_type, size_or_initializer)
1049
1050 Return a ctypes array allocated from shared memory.
1051
1052 *typecode_or_type* determines the type of the elements of the returned array:
1053 it is either a ctypes type or a one character typecode of the kind used by
1054 the :mod:`array` module. If *size_or_initializer* is an integer then it
1055 determines the length of the array, and the array will be initially zeroed.
1056 Otherwise *size_or_initializer* is a sequence which is used to initialize the
1057 array and whose length determines the length of the array.
1058
1059 Note that setting and getting an element is potentially non-atomic -- use
1060 :func:`Array` instead to make sure that access is automatically synchronized
1061 using a lock.
1062
1063.. function:: RawValue(typecode_or_type, *args)
1064
1065 Return a ctypes object allocated from shared memory.
1066
1067 *typecode_or_type* determines the type of the returned object: it is either a
1068 ctypes type or a one character typecode of the kind used by the :mod:`array`
Jesse Noller6ab22152009-01-18 02:45:38 +00001069 module. *\*args* is passed on to the constructor for the type.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001070
1071 Note that setting and getting the value is potentially non-atomic -- use
1072 :func:`Value` instead to make sure that access is automatically synchronized
1073 using a lock.
1074
Georg Brandlb053f992008-11-22 08:34:14 +00001075 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001076 attributes which allow one to use it to store and retrieve strings -- see
1077 documentation for :mod:`ctypes`.
1078
Jesse Noller6ab22152009-01-18 02:45:38 +00001079.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001080
1081 The same as :func:`RawArray` except that depending on the value of *lock* a
1082 process-safe synchronization wrapper may be returned instead of a raw ctypes
1083 array.
1084
1085 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001086 synchronize access to the value. If *lock* is a
1087 :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
1088 then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001089 value. If *lock* is ``False`` then access to the returned object will not be
1090 automatically protected by a lock, so it will not necessarily be
1091 "process-safe".
1092
1093 Note that *lock* is a keyword-only argument.
1094
1095.. function:: Value(typecode_or_type, *args[, lock])
1096
1097 The same as :func:`RawValue` except that depending on the value of *lock* a
1098 process-safe synchronization wrapper may be returned instead of a raw ctypes
1099 object.
1100
1101 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001102 synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or
1103 :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001104 value. If *lock* is ``False`` then access to the returned object will not be
1105 automatically protected by a lock, so it will not necessarily be
1106 "process-safe".
1107
1108 Note that *lock* is a keyword-only argument.
1109
1110.. function:: copy(obj)
1111
1112 Return a ctypes object allocated from shared memory which is a copy of the
1113 ctypes object *obj*.
1114
1115.. function:: synchronized(obj[, lock])
1116
1117 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1118 synchronize access. If *lock* is ``None`` (the default) then a
1119 :class:`multiprocessing.RLock` object is created automatically.
1120
1121 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001122 object it wraps: :meth:`get_obj` returns the wrapped object and
1123 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001124
1125 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001126 than accessing the raw ctypes object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001127
1128
1129The table below compares the syntax for creating shared ctypes objects from
1130shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1131subclass of :class:`ctypes.Structure`.)
1132
1133==================== ========================== ===========================
1134ctypes sharedctypes using type sharedctypes using typecode
1135==================== ========================== ===========================
1136c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1137MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1138(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1139(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1140==================== ========================== ===========================
1141
1142
1143Below is an example where a number of ctypes objects are modified by a child
1144process::
1145
1146 from multiprocessing import Process, Lock
1147 from multiprocessing.sharedctypes import Value, Array
1148 from ctypes import Structure, c_double
1149
1150 class Point(Structure):
1151 _fields_ = [('x', c_double), ('y', c_double)]
1152
1153 def modify(n, x, s, A):
1154 n.value **= 2
1155 x.value **= 2
1156 s.value = s.value.upper()
1157 for a in A:
1158 a.x **= 2
1159 a.y **= 2
1160
1161 if __name__ == '__main__':
1162 lock = Lock()
1163
1164 n = Value('i', 7)
R. David Murray636b23a2009-04-28 16:08:18 +00001165 x = Value(c_double, 1.0/3.0, lock=False)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001166 s = Array('c', 'hello world', lock=lock)
1167 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1168
1169 p = Process(target=modify, args=(n, x, s, A))
1170 p.start()
1171 p.join()
1172
1173 print n.value
1174 print x.value
1175 print s.value
1176 print [(a.x, a.y) for a in A]
1177
1178
1179.. highlightlang:: none
1180
1181The results printed are ::
1182
1183 49
1184 0.1111111111111111
1185 HELLO WORLD
1186 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1187
1188.. highlightlang:: python
1189
1190
1191.. _multiprocessing-managers:
1192
1193Managers
1194~~~~~~~~
1195
1196Managers provide a way to create data which can be shared between different
1197processes. A manager object controls a server process which manages *shared
1198objects*. Other processes can access the shared objects by using proxies.
1199
1200.. function:: multiprocessing.Manager()
1201
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001202 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1203 can be used for sharing objects between processes. The returned manager
1204 object corresponds to a spawned child process and has methods which will
1205 create shared objects and return corresponding proxies.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001206
1207.. module:: multiprocessing.managers
1208 :synopsis: Share data between process with shared objects.
1209
1210Manager processes will be shutdown as soon as they are garbage collected or
1211their parent process exits. The manager classes are defined in the
1212:mod:`multiprocessing.managers` module:
1213
1214.. class:: BaseManager([address[, authkey]])
1215
1216 Create a BaseManager object.
1217
Jack Diederich1605b332010-02-23 17:23:30 +00001218 Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001219 that the manager object refers to a started manager process.
1220
1221 *address* is the address on which the manager process listens for new
1222 connections. If *address* is ``None`` then an arbitrary one is chosen.
1223
1224 *authkey* is the authentication key which will be used to check the validity
1225 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001226 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001227 must be a string.
1228
Jesse Noller7152f6d2009-04-02 05:17:26 +00001229 .. method:: start([initializer[, initargs]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001230
Jesse Noller7152f6d2009-04-02 05:17:26 +00001231 Start a subprocess to start the manager. If *initializer* is not ``None``
1232 then the subprocess will call ``initializer(*initargs)`` when it starts.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001233
Jesse Nollera280fd72008-11-28 18:22:54 +00001234 .. method:: get_server()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001235
Jesse Nollera280fd72008-11-28 18:22:54 +00001236 Returns a :class:`Server` object which represents the actual server under
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001237 the control of the Manager. The :class:`Server` object supports the
R. David Murray636b23a2009-04-28 16:08:18 +00001238 :meth:`serve_forever` method::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001239
Georg Brandlfc29f272009-01-02 20:25:14 +00001240 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001241 >>> manager = BaseManager(address=('', 50000), authkey='abc')
1242 >>> server = manager.get_server()
1243 >>> server.serve_forever()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001244
R. David Murray636b23a2009-04-28 16:08:18 +00001245 :class:`Server` additionally has an :attr:`address` attribute.
Jesse Nollera280fd72008-11-28 18:22:54 +00001246
1247 .. method:: connect()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001248
R. David Murray636b23a2009-04-28 16:08:18 +00001249 Connect a local manager object to a remote manager process::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001250
Jesse Nollera280fd72008-11-28 18:22:54 +00001251 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001252 >>> m = BaseManager(address=('127.0.0.1', 5000), authkey='abc')
Jesse Nollera280fd72008-11-28 18:22:54 +00001253 >>> m.connect()
1254
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001255 .. method:: shutdown()
1256
1257 Stop the process used by the manager. This is only available if
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001258 :meth:`start` has been used to start the server process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001259
1260 This can be called multiple times.
1261
1262 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1263
1264 A classmethod which can be used for registering a type or callable with
1265 the manager class.
1266
1267 *typeid* is a "type identifier" which is used to identify a particular
1268 type of shared object. This must be a string.
1269
1270 *callable* is a callable used for creating objects for this type
1271 identifier. If a manager instance will be created using the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001272 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001273 ``False`` then this can be left as ``None``.
1274
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001275 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1276 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1277 class is created automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001278
1279 *exposed* is used to specify a sequence of method names which proxies for
1280 this typeid should be allowed to access using
Ezio Melotti207b5f42014-02-15 16:58:52 +02001281 :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001282 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1283 where no exposed list is specified, all "public methods" of the shared
1284 object will be accessible. (Here a "public method" means any attribute
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001285 which has a :meth:`~object.__call__` method and whose name does not begin
1286 with ``'_'``.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001287
1288 *method_to_typeid* is a mapping used to specify the return type of those
1289 exposed methods which should return a proxy. It maps method names to
1290 typeid strings. (If *method_to_typeid* is ``None`` then
1291 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1292 method's name is not a key of this mapping or if the mapping is ``None``
1293 then the object returned by the method will be copied by value.
1294
1295 *create_method* determines whether a method should be created with name
1296 *typeid* which can be used to tell the server process to create a new
1297 shared object and return a proxy for it. By default it is ``True``.
1298
1299 :class:`BaseManager` instances also have one read-only property:
1300
1301 .. attribute:: address
1302
1303 The address used by the manager.
1304
1305
1306.. class:: SyncManager
1307
1308 A subclass of :class:`BaseManager` which can be used for the synchronization
1309 of processes. Objects of this type are returned by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001310 :func:`multiprocessing.Manager`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001311
1312 It also supports creation of shared lists and dictionaries.
1313
1314 .. method:: BoundedSemaphore([value])
1315
1316 Create a shared :class:`threading.BoundedSemaphore` object and return a
1317 proxy for it.
1318
1319 .. method:: Condition([lock])
1320
1321 Create a shared :class:`threading.Condition` object and return a proxy for
1322 it.
1323
1324 If *lock* is supplied then it should be a proxy for a
1325 :class:`threading.Lock` or :class:`threading.RLock` object.
1326
1327 .. method:: Event()
1328
1329 Create a shared :class:`threading.Event` object and return a proxy for it.
1330
1331 .. method:: Lock()
1332
1333 Create a shared :class:`threading.Lock` object and return a proxy for it.
1334
1335 .. method:: Namespace()
1336
1337 Create a shared :class:`Namespace` object and return a proxy for it.
1338
1339 .. method:: Queue([maxsize])
1340
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001341 Create a shared :class:`Queue.Queue` object and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001342
1343 .. method:: RLock()
1344
1345 Create a shared :class:`threading.RLock` object and return a proxy for it.
1346
1347 .. method:: Semaphore([value])
1348
1349 Create a shared :class:`threading.Semaphore` object and return a proxy for
1350 it.
1351
1352 .. method:: Array(typecode, sequence)
1353
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001354 Create an array and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001355
1356 .. method:: Value(typecode, value)
1357
1358 Create an object with a writable ``value`` attribute and return a proxy
1359 for it.
1360
1361 .. method:: dict()
1362 dict(mapping)
1363 dict(sequence)
1364
1365 Create a shared ``dict`` object and return a proxy for it.
1366
1367 .. method:: list()
1368 list(sequence)
1369
1370 Create a shared ``list`` object and return a proxy for it.
1371
Georg Brandl78f11ed2010-11-26 07:34:20 +00001372 .. note::
1373
1374 Modifications to mutable values or items in dict and list proxies will not
1375 be propagated through the manager, because the proxy has no way of knowing
1376 when its values or items are modified. To modify such an item, you can
1377 re-assign the modified object to the container proxy::
1378
1379 # create a list proxy and append a mutable object (a dictionary)
1380 lproxy = manager.list()
1381 lproxy.append({})
1382 # now mutate the dictionary
1383 d = lproxy[0]
1384 d['a'] = 1
1385 d['b'] = 2
1386 # at this point, the changes to d are not yet synced, but by
1387 # reassigning the dictionary, the proxy is notified of the change
1388 lproxy[0] = d
1389
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001390
1391Namespace objects
1392>>>>>>>>>>>>>>>>>
1393
1394A namespace object has no public methods, but does have writable attributes.
1395Its representation shows the values of its attributes.
1396
1397However, when using a proxy for a namespace object, an attribute beginning with
R. David Murray636b23a2009-04-28 16:08:18 +00001398``'_'`` will be an attribute of the proxy and not an attribute of the referent:
1399
1400.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001401
1402 >>> manager = multiprocessing.Manager()
1403 >>> Global = manager.Namespace()
1404 >>> Global.x = 10
1405 >>> Global.y = 'hello'
1406 >>> Global._z = 12.3 # this is an attribute of the proxy
1407 >>> print Global
1408 Namespace(x=10, y='hello')
1409
1410
1411Customized managers
1412>>>>>>>>>>>>>>>>>>>
1413
1414To create one's own manager, one creates a subclass of :class:`BaseManager` and
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001415uses the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001416callables with the manager class. For example::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001417
1418 from multiprocessing.managers import BaseManager
1419
1420 class MathsClass(object):
1421 def add(self, x, y):
1422 return x + y
1423 def mul(self, x, y):
1424 return x * y
1425
1426 class MyManager(BaseManager):
1427 pass
1428
1429 MyManager.register('Maths', MathsClass)
1430
1431 if __name__ == '__main__':
1432 manager = MyManager()
1433 manager.start()
1434 maths = manager.Maths()
1435 print maths.add(4, 3) # prints 7
1436 print maths.mul(7, 8) # prints 56
1437
1438
1439Using a remote manager
1440>>>>>>>>>>>>>>>>>>>>>>
1441
1442It is possible to run a manager server on one machine and have clients use it
1443from other machines (assuming that the firewalls involved allow it).
1444
1445Running the following commands creates a server for a single shared queue which
1446remote clients can access::
1447
1448 >>> from multiprocessing.managers import BaseManager
1449 >>> import Queue
1450 >>> queue = Queue.Queue()
1451 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001452 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001453 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Nollera280fd72008-11-28 18:22:54 +00001454 >>> s = m.get_server()
R. David Murray636b23a2009-04-28 16:08:18 +00001455 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001456
1457One client can access the server as follows::
1458
1459 >>> from multiprocessing.managers import BaseManager
1460 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001461 >>> QueueManager.register('get_queue')
1462 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1463 >>> m.connect()
1464 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001465 >>> queue.put('hello')
1466
1467Another client can also use it::
1468
1469 >>> from multiprocessing.managers import BaseManager
1470 >>> class QueueManager(BaseManager): pass
R. David Murray636b23a2009-04-28 16:08:18 +00001471 >>> QueueManager.register('get_queue')
1472 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1473 >>> m.connect()
1474 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001475 >>> queue.get()
1476 'hello'
1477
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001478Local processes can also access that queue, using the code from above on the
Jesse Nollera280fd72008-11-28 18:22:54 +00001479client to access it remotely::
1480
1481 >>> from multiprocessing import Process, Queue
1482 >>> from multiprocessing.managers import BaseManager
1483 >>> class Worker(Process):
1484 ... def __init__(self, q):
1485 ... self.q = q
1486 ... super(Worker, self).__init__()
1487 ... def run(self):
1488 ... self.q.put('local hello')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001489 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001490 >>> queue = Queue()
1491 >>> w = Worker(queue)
1492 >>> w.start()
1493 >>> class QueueManager(BaseManager): pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001494 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001495 >>> QueueManager.register('get_queue', callable=lambda: queue)
1496 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1497 >>> s = m.get_server()
1498 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001499
1500Proxy Objects
1501~~~~~~~~~~~~~
1502
1503A proxy is an object which *refers* to a shared object which lives (presumably)
1504in a different process. The shared object is said to be the *referent* of the
1505proxy. Multiple proxy objects may have the same referent.
1506
1507A proxy object has methods which invoke corresponding methods of its referent
1508(although not every method of the referent will necessarily be available through
1509the proxy). A proxy can usually be used in most of the same ways that its
R. David Murray636b23a2009-04-28 16:08:18 +00001510referent can:
1511
1512.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001513
1514 >>> from multiprocessing import Manager
1515 >>> manager = Manager()
1516 >>> l = manager.list([i*i for i in range(10)])
1517 >>> print l
1518 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1519 >>> print repr(l)
R. David Murray636b23a2009-04-28 16:08:18 +00001520 <ListProxy object, typeid 'list' at 0x...>
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001521 >>> l[4]
1522 16
1523 >>> l[2:5]
1524 [4, 9, 16]
1525
1526Notice that applying :func:`str` to a proxy will return the representation of
1527the referent, whereas applying :func:`repr` will return the representation of
1528the proxy.
1529
1530An important feature of proxy objects is that they are picklable so they can be
1531passed between processes. Note, however, that if a proxy is sent to the
1532corresponding manager's process then unpickling it will produce the referent
R. David Murray636b23a2009-04-28 16:08:18 +00001533itself. This means, for example, that one shared object can contain a second:
1534
1535.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001536
1537 >>> a = manager.list()
1538 >>> b = manager.list()
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001539 >>> a.append(b) # referent of a now contains referent of b
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001540 >>> print a, b
1541 [[]] []
1542 >>> b.append('hello')
1543 >>> print a, b
1544 [['hello']] ['hello']
1545
1546.. note::
1547
1548 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
R. David Murray636b23a2009-04-28 16:08:18 +00001549 by value. So, for instance, we have:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001550
R. David Murray636b23a2009-04-28 16:08:18 +00001551 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001552
R. David Murray636b23a2009-04-28 16:08:18 +00001553 >>> manager.list([1,2,3]) == [1,2,3]
1554 False
1555
1556 One should just use a copy of the referent instead when making comparisons.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001557
1558.. class:: BaseProxy
1559
1560 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1561
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001562 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001563
1564 Call and return the result of a method of the proxy's referent.
1565
1566 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1567
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001568 proxy._callmethod(methodname, args, kwds)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001569
1570 will evaluate the expression ::
1571
1572 getattr(obj, methodname)(*args, **kwds)
1573
1574 in the manager's process.
1575
1576 The returned value will be a copy of the result of the call or a proxy to
1577 a new shared object -- see documentation for the *method_to_typeid*
1578 argument of :meth:`BaseManager.register`.
1579
Ezio Melotti1e87da12011-10-19 10:39:35 +03001580 If an exception is raised by the call, then is re-raised by
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001581 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001582 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001583 raised by :meth:`_callmethod`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001584
1585 Note in particular that an exception will be raised if *methodname* has
1586 not been *exposed*
1587
R. David Murray636b23a2009-04-28 16:08:18 +00001588 An example of the usage of :meth:`_callmethod`:
1589
1590 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001591
1592 >>> l = manager.list(range(10))
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001593 >>> l._callmethod('__len__')
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001594 10
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001595 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001596 [2, 3, 4, 5, 6]
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001597 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001598 Traceback (most recent call last):
1599 ...
1600 IndexError: list index out of range
1601
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001602 .. method:: _getvalue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001603
1604 Return a copy of the referent.
1605
1606 If the referent is unpicklable then this will raise an exception.
1607
1608 .. method:: __repr__
1609
1610 Return a representation of the proxy object.
1611
1612 .. method:: __str__
1613
1614 Return the representation of the referent.
1615
1616
1617Cleanup
1618>>>>>>>
1619
1620A proxy object uses a weakref callback so that when it gets garbage collected it
1621deregisters itself from the manager which owns its referent.
1622
1623A shared object gets deleted from the manager process when there are no longer
1624any proxies referring to it.
1625
1626
1627Process Pools
1628~~~~~~~~~~~~~
1629
1630.. module:: multiprocessing.pool
1631 :synopsis: Create pools of processes.
1632
1633One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001634with the :class:`Pool` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001635
Jesse Noller654ade32010-01-27 03:05:57 +00001636.. class:: multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001637
1638 A process pool object which controls a pool of worker processes to which jobs
1639 can be submitted. It supports asynchronous results with timeouts and
1640 callbacks and has a parallel map implementation.
1641
1642 *processes* is the number of worker processes to use. If *processes* is
1643 ``None`` then the number returned by :func:`cpu_count` is used. If
1644 *initializer* is not ``None`` then each worker process will call
1645 ``initializer(*initargs)`` when it starts.
1646
Richard Oudkerk49032532013-07-02 12:31:50 +01001647 Note that the methods of the pool object should only be called by
1648 the process which created the pool.
1649
Georg Brandl92e69722010-10-17 06:21:30 +00001650 .. versionadded:: 2.7
1651 *maxtasksperchild* is the number of tasks a worker process can complete
1652 before it will exit and be replaced with a fresh worker process, to enable
1653 unused resources to be freed. The default *maxtasksperchild* is None, which
1654 means worker processes will live as long as the pool.
Jesse Noller654ade32010-01-27 03:05:57 +00001655
1656 .. note::
1657
Georg Brandl92e69722010-10-17 06:21:30 +00001658 Worker processes within a :class:`Pool` typically live for the complete
1659 duration of the Pool's work queue. A frequent pattern found in other
1660 systems (such as Apache, mod_wsgi, etc) to free resources held by
1661 workers is to allow a worker within a pool to complete only a set
1662 amount of work before being exiting, being cleaned up and a new
1663 process spawned to replace the old one. The *maxtasksperchild*
1664 argument to the :class:`Pool` exposes this ability to the end user.
Jesse Noller654ade32010-01-27 03:05:57 +00001665
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001666 .. method:: apply(func[, args[, kwds]])
1667
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001668 Equivalent of the :func:`apply` built-in function. It blocks until the
1669 result is ready, so :meth:`apply_async` is better suited for performing
1670 work in parallel. Additionally, *func* is only executed in one of the
1671 workers of the pool.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001672
1673 .. method:: apply_async(func[, args[, kwds[, callback]]])
1674
1675 A variant of the :meth:`apply` method which returns a result object.
1676
1677 If *callback* is specified then it should be a callable which accepts a
1678 single argument. When the result becomes ready *callback* is applied to
1679 it (unless the call failed). *callback* should complete immediately since
1680 otherwise the thread which handles the results will get blocked.
1681
1682 .. method:: map(func, iterable[, chunksize])
1683
Georg Brandld7d4fd72009-07-26 14:37:28 +00001684 A parallel equivalent of the :func:`map` built-in function (it supports only
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001685 one *iterable* argument though). It blocks until the result is ready.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001686
1687 This method chops the iterable into a number of chunks which it submits to
1688 the process pool as separate tasks. The (approximate) size of these
1689 chunks can be specified by setting *chunksize* to a positive integer.
1690
Senthil Kumaran0fc13ae2011-11-03 02:02:38 +08001691 .. method:: map_async(func, iterable[, chunksize[, callback]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001692
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001693 A variant of the :meth:`.map` method which returns a result object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001694
1695 If *callback* is specified then it should be a callable which accepts a
1696 single argument. When the result becomes ready *callback* is applied to
1697 it (unless the call failed). *callback* should complete immediately since
1698 otherwise the thread which handles the results will get blocked.
1699
1700 .. method:: imap(func, iterable[, chunksize])
1701
1702 An equivalent of :func:`itertools.imap`.
1703
1704 The *chunksize* argument is the same as the one used by the :meth:`.map`
1705 method. For very long iterables using a large value for *chunksize* can
Ezio Melotti1e87da12011-10-19 10:39:35 +03001706 make the job complete **much** faster than using the default value of
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001707 ``1``.
1708
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001709 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001710 returned by the :meth:`imap` method has an optional *timeout* parameter:
1711 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1712 result cannot be returned within *timeout* seconds.
1713
1714 .. method:: imap_unordered(func, iterable[, chunksize])
1715
1716 The same as :meth:`imap` except that the ordering of the results from the
1717 returned iterator should be considered arbitrary. (Only when there is
1718 only one worker process is the order guaranteed to be "correct".)
1719
1720 .. method:: close()
1721
1722 Prevents any more tasks from being submitted to the pool. Once all the
1723 tasks have been completed the worker processes will exit.
1724
1725 .. method:: terminate()
1726
1727 Stops the worker processes immediately without completing outstanding
1728 work. When the pool object is garbage collected :meth:`terminate` will be
1729 called immediately.
1730
1731 .. method:: join()
1732
1733 Wait for the worker processes to exit. One must call :meth:`close` or
1734 :meth:`terminate` before using :meth:`join`.
1735
1736
1737.. class:: AsyncResult
1738
1739 The class of the result returned by :meth:`Pool.apply_async` and
1740 :meth:`Pool.map_async`.
1741
Jesse Nollera280fd72008-11-28 18:22:54 +00001742 .. method:: get([timeout])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001743
1744 Return the result when it arrives. If *timeout* is not ``None`` and the
1745 result does not arrive within *timeout* seconds then
1746 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1747 an exception then that exception will be reraised by :meth:`get`.
1748
1749 .. method:: wait([timeout])
1750
1751 Wait until the result is available or until *timeout* seconds pass.
1752
1753 .. method:: ready()
1754
1755 Return whether the call has completed.
1756
1757 .. method:: successful()
1758
1759 Return whether the call completed without raising an exception. Will
1760 raise :exc:`AssertionError` if the result is not ready.
1761
1762The following example demonstrates the use of a pool::
1763
1764 from multiprocessing import Pool
1765
1766 def f(x):
1767 return x*x
1768
1769 if __name__ == '__main__':
1770 pool = Pool(processes=4) # start 4 worker processes
1771
Jesse Nollera280fd72008-11-28 18:22:54 +00001772 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001773 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
1774
1775 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
1776
1777 it = pool.imap(f, range(10))
1778 print it.next() # prints "0"
1779 print it.next() # prints "1"
1780 print it.next(timeout=1) # prints "4" unless your computer is *very* slow
1781
1782 import time
Jesse Nollera280fd72008-11-28 18:22:54 +00001783 result = pool.apply_async(time.sleep, (10,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001784 print result.get(timeout=1) # raises TimeoutError
1785
1786
1787.. _multiprocessing-listeners-clients:
1788
1789Listeners and Clients
1790~~~~~~~~~~~~~~~~~~~~~
1791
1792.. module:: multiprocessing.connection
1793 :synopsis: API for dealing with sockets.
1794
1795Usually message passing between processes is done using queues or by using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001796:class:`~multiprocessing.Connection` objects returned by
1797:func:`~multiprocessing.Pipe`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001798
1799However, the :mod:`multiprocessing.connection` module allows some extra
1800flexibility. It basically gives a high level message oriented API for dealing
1801with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001802authentication* using the :mod:`hmac` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001803
1804
1805.. function:: deliver_challenge(connection, authkey)
1806
1807 Send a randomly generated message to the other end of the connection and wait
1808 for a reply.
1809
1810 If the reply matches the digest of the message using *authkey* as the key
1811 then a welcome message is sent to the other end of the connection. Otherwise
1812 :exc:`AuthenticationError` is raised.
1813
Ezio Melotti3218f652013-04-10 17:59:20 +03001814.. function:: answer_challenge(connection, authkey)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001815
1816 Receive a message, calculate the digest of the message using *authkey* as the
1817 key, and then send the digest back.
1818
1819 If a welcome message is not received, then :exc:`AuthenticationError` is
1820 raised.
1821
1822.. function:: Client(address[, family[, authenticate[, authkey]]])
1823
1824 Attempt to set up a connection to the listener which is using address
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001825 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001826
1827 The type of the connection is determined by *family* argument, but this can
1828 generally be omitted since it can usually be inferred from the format of
1829 *address*. (See :ref:`multiprocessing-address-formats`)
1830
Jesse Noller34116922009-06-29 18:24:26 +00001831 If *authenticate* is ``True`` or *authkey* is a string then digest
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001832 authentication is used. The key used for authentication will be either
Benjamin Peterson73641d72008-08-20 14:07:59 +00001833 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001834 If authentication fails then :exc:`AuthenticationError` is raised. See
1835 :ref:`multiprocessing-auth-keys`.
1836
1837.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1838
1839 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1840 connections.
1841
1842 *address* is the address to be used by the bound socket or named pipe of the
1843 listener object.
1844
Jesse Nollerb12e79d2009-04-01 16:42:19 +00001845 .. note::
1846
1847 If an address of '0.0.0.0' is used, the address will not be a connectable
1848 end point on Windows. If you require a connectable end-point,
1849 you should use '127.0.0.1'.
1850
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001851 *family* is the type of socket (or named pipe) to use. This can be one of
1852 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1853 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1854 the first is guaranteed to be available. If *family* is ``None`` then the
1855 family is inferred from the format of *address*. If *address* is also
1856 ``None`` then a default is chosen. This default is the family which is
1857 assumed to be the fastest available. See
1858 :ref:`multiprocessing-address-formats`. Note that if *family* is
1859 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1860 private temporary directory created using :func:`tempfile.mkstemp`.
1861
1862 If the listener object uses a socket then *backlog* (1 by default) is passed
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001863 to the :meth:`~socket.socket.listen` method of the socket once it has been
1864 bound.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001865
1866 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1867 ``None`` then digest authentication is used.
1868
1869 If *authkey* is a string then it will be used as the authentication key;
1870 otherwise it must be *None*.
1871
1872 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001873 ``current_process().authkey`` is used as the authentication key. If
Jesse Noller34116922009-06-29 18:24:26 +00001874 *authkey* is ``None`` and *authenticate* is ``False`` then no
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001875 authentication is done. If authentication fails then
1876 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1877
1878 .. method:: accept()
1879
1880 Accept a connection on the bound socket or named pipe of the listener
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001881 object and return a :class:`~multiprocessing.Connection` object. If
1882 authentication is attempted and fails, then
1883 :exc:`~multiprocessing.AuthenticationError` is raised.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001884
1885 .. method:: close()
1886
1887 Close the bound socket or named pipe of the listener object. This is
1888 called automatically when the listener is garbage collected. However it
1889 is advisable to call it explicitly.
1890
1891 Listener objects have the following read-only properties:
1892
1893 .. attribute:: address
1894
1895 The address which is being used by the Listener object.
1896
1897 .. attribute:: last_accepted
1898
1899 The address from which the last accepted connection came. If this is
1900 unavailable then it is ``None``.
1901
1902
1903The module defines two exceptions:
1904
1905.. exception:: AuthenticationError
1906
1907 Exception raised when there is an authentication error.
1908
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001909
1910**Examples**
1911
1912The following server code creates a listener which uses ``'secret password'`` as
1913an authentication key. It then waits for a connection and sends some data to
1914the client::
1915
1916 from multiprocessing.connection import Listener
1917 from array import array
1918
1919 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
1920 listener = Listener(address, authkey='secret password')
1921
1922 conn = listener.accept()
1923 print 'connection accepted from', listener.last_accepted
1924
1925 conn.send([2.25, None, 'junk', float])
1926
1927 conn.send_bytes('hello')
1928
1929 conn.send_bytes(array('i', [42, 1729]))
1930
1931 conn.close()
1932 listener.close()
1933
1934The following code connects to the server and receives some data from the
1935server::
1936
1937 from multiprocessing.connection import Client
1938 from array import array
1939
1940 address = ('localhost', 6000)
1941 conn = Client(address, authkey='secret password')
1942
1943 print conn.recv() # => [2.25, None, 'junk', float]
1944
1945 print conn.recv_bytes() # => 'hello'
1946
1947 arr = array('i', [0, 0, 0, 0, 0])
1948 print conn.recv_bytes_into(arr) # => 8
1949 print arr # => array('i', [42, 1729, 0, 0, 0])
1950
1951 conn.close()
1952
1953
1954.. _multiprocessing-address-formats:
1955
1956Address Formats
1957>>>>>>>>>>>>>>>
1958
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001959* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001960 *hostname* is a string and *port* is an integer.
1961
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001962* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001963 filesystem.
1964
1965* An ``'AF_PIPE'`` address is a string of the form
Georg Brandl6b28f392008-12-27 19:06:04 +00001966 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandlfc29f272009-01-02 20:25:14 +00001967 pipe on a remote computer called *ServerName* one should use an address of the
Georg Brandldd7e3132009-01-04 10:24:09 +00001968 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001969
1970Note that any string beginning with two backslashes is assumed by default to be
1971an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
1972
1973
1974.. _multiprocessing-auth-keys:
1975
1976Authentication keys
1977~~~~~~~~~~~~~~~~~~~
1978
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001979When one uses :meth:`Connection.recv <multiprocessing.Connection.recv>`, the
1980data received is automatically
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001981unpickled. Unfortunately unpickling data from an untrusted source is a security
1982risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
1983to provide digest authentication.
1984
1985An authentication key is a string which can be thought of as a password: once a
1986connection is established both ends will demand proof that the other knows the
1987authentication key. (Demonstrating that both ends are using the same key does
1988**not** involve sending the key over the connection.)
1989
1990If authentication is requested but do authentication key is specified then the
Benjamin Peterson73641d72008-08-20 14:07:59 +00001991return value of ``current_process().authkey`` is used (see
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001992:class:`~multiprocessing.Process`). This value will automatically inherited by
1993any :class:`~multiprocessing.Process` object that the current process creates.
1994This means that (by default) all processes of a multi-process program will share
1995a single authentication key which can be used when setting up connections
Andrew M. Kuchlinga178a692009-04-03 21:45:29 +00001996between themselves.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001997
1998Suitable authentication keys can also be generated by using :func:`os.urandom`.
1999
2000
2001Logging
2002~~~~~~~
2003
2004Some support for logging is available. Note, however, that the :mod:`logging`
2005package does not use process shared locks so it is possible (depending on the
2006handler type) for messages from different processes to get mixed up.
2007
2008.. currentmodule:: multiprocessing
2009.. function:: get_logger()
2010
2011 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
2012 will be created.
2013
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002014 When first created the logger has level :data:`logging.NOTSET` and no
2015 default handler. Messages sent to this logger will not by default propagate
2016 to the root logger.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002017
2018 Note that on Windows child processes will only inherit the level of the
2019 parent process's logger -- any other customization of the logger will not be
2020 inherited.
2021
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002022.. currentmodule:: multiprocessing
2023.. function:: log_to_stderr()
2024
2025 This function performs a call to :func:`get_logger` but in addition to
2026 returning the logger created by get_logger, it adds a handler which sends
2027 output to :data:`sys.stderr` using format
2028 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2029
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002030Below is an example session with logging turned on::
2031
Georg Brandl19cc9442008-10-16 21:36:39 +00002032 >>> import multiprocessing, logging
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002033 >>> logger = multiprocessing.log_to_stderr()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002034 >>> logger.setLevel(logging.INFO)
2035 >>> logger.warning('doomed')
2036 [WARNING/MainProcess] doomed
Georg Brandl19cc9442008-10-16 21:36:39 +00002037 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002038 [INFO/SyncManager-...] child process calling self.run()
2039 [INFO/SyncManager-...] created temp directory /.../pymp-...
2040 [INFO/SyncManager-...] manager serving at '/.../listener-...'
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002041 >>> del m
2042 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002043 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002044
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002045In addition to having these two logging functions, the multiprocessing also
2046exposes two additional logging level attributes. These are :const:`SUBWARNING`
2047and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
2048normal level hierarchy.
2049
2050+----------------+----------------+
2051| Level | Numeric value |
2052+================+================+
2053| ``SUBWARNING`` | 25 |
2054+----------------+----------------+
2055| ``SUBDEBUG`` | 5 |
2056+----------------+----------------+
2057
2058For a full table of logging levels, see the :mod:`logging` module.
2059
2060These additional logging levels are used primarily for certain debug messages
2061within the multiprocessing module. Below is the same example as above, except
2062with :const:`SUBDEBUG` enabled::
2063
2064 >>> import multiprocessing, logging
2065 >>> logger = multiprocessing.log_to_stderr()
2066 >>> logger.setLevel(multiprocessing.SUBDEBUG)
2067 >>> logger.warning('doomed')
2068 [WARNING/MainProcess] doomed
2069 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002070 [INFO/SyncManager-...] child process calling self.run()
2071 [INFO/SyncManager-...] created temp directory /.../pymp-...
2072 [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002073 >>> del m
2074 [SUBDEBUG/MainProcess] finalizer calling ...
2075 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002076 [DEBUG/SyncManager-...] manager received shutdown message
2077 [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
2078 [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
2079 [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
2080 [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
2081 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002082
2083The :mod:`multiprocessing.dummy` module
2084~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2085
2086.. module:: multiprocessing.dummy
2087 :synopsis: Dumb wrapper around threading.
2088
2089:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002090no more than a wrapper around the :mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002091
2092
2093.. _multiprocessing-programming:
2094
2095Programming guidelines
2096----------------------
2097
2098There are certain guidelines and idioms which should be adhered to when using
2099:mod:`multiprocessing`.
2100
2101
2102All platforms
2103~~~~~~~~~~~~~
2104
2105Avoid shared state
2106
2107 As far as possible one should try to avoid shifting large amounts of data
2108 between processes.
2109
2110 It is probably best to stick to using queues or pipes for communication
2111 between processes rather than using the lower level synchronization
2112 primitives from the :mod:`threading` module.
2113
2114Picklability
2115
2116 Ensure that the arguments to the methods of proxies are picklable.
2117
2118Thread safety of proxies
2119
2120 Do not use a proxy object from more than one thread unless you protect it
2121 with a lock.
2122
2123 (There is never a problem with different processes using the *same* proxy.)
2124
2125Joining zombie processes
2126
2127 On Unix when a process finishes but has not been joined it becomes a zombie.
2128 There should never be very many because each time a new process starts (or
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002129 :func:`~multiprocessing.active_children` is called) all completed processes
2130 which have not yet been joined will be joined. Also calling a finished
2131 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
2132 join the process. Even so it is probably good
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002133 practice to explicitly join all the processes that you start.
2134
2135Better to inherit than pickle/unpickle
2136
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002137 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002138 that child processes can use them. However, one should generally avoid
2139 sending shared objects to other processes using pipes or queues. Instead
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002140 you should arrange the program so that a process which needs access to a
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002141 shared resource created elsewhere can inherit it from an ancestor process.
2142
2143Avoid terminating processes
2144
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002145 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
2146 method to stop a process is liable to
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002147 cause any shared resources (such as locks, semaphores, pipes and queues)
2148 currently being used by the process to become broken or unavailable to other
2149 processes.
2150
2151 Therefore it is probably best to only consider using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002152 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
2153 which never use any shared resources.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002154
2155Joining processes that use queues
2156
2157 Bear in mind that a process that has put items in a queue will wait before
2158 terminating until all the buffered items are fed by the "feeder" thread to
2159 the underlying pipe. (The child process can call the
Sandro Tosi8b48c662012-02-25 19:35:16 +01002160 :meth:`~multiprocessing.Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002161
2162 This means that whenever you use a queue you need to make sure that all
2163 items which have been put on the queue will eventually be removed before the
2164 process is joined. Otherwise you cannot be sure that processes which have
2165 put items on the queue will terminate. Remember also that non-daemonic
Zachary Ware06b74a72014-10-03 10:55:12 -05002166 processes will be joined automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002167
2168 An example which will deadlock is the following::
2169
2170 from multiprocessing import Process, Queue
2171
2172 def f(q):
2173 q.put('X' * 1000000)
2174
2175 if __name__ == '__main__':
2176 queue = Queue()
2177 p = Process(target=f, args=(queue,))
2178 p.start()
2179 p.join() # this deadlocks
2180 obj = queue.get()
2181
Zachary Ware06b74a72014-10-03 10:55:12 -05002182 A fix here would be to swap the last two lines (or simply remove the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002183 ``p.join()`` line).
2184
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002185Explicitly pass resources to child processes
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002186
2187 On Unix a child process can make use of a shared resource created in a
2188 parent process using a global resource. However, it is better to pass the
2189 object as an argument to the constructor for the child process.
2190
2191 Apart from making the code (potentially) compatible with Windows this also
2192 ensures that as long as the child process is still alive the object will not
2193 be garbage collected in the parent process. This might be important if some
2194 resource is freed when the object is garbage collected in the parent
2195 process.
2196
2197 So for instance ::
2198
2199 from multiprocessing import Process, Lock
2200
2201 def f():
2202 ... do something using "lock" ...
2203
2204 if __name__ == '__main__':
2205 lock = Lock()
2206 for i in range(10):
2207 Process(target=f).start()
2208
2209 should be rewritten as ::
2210
2211 from multiprocessing import Process, Lock
2212
2213 def f(l):
2214 ... do something using "l" ...
2215
2216 if __name__ == '__main__':
2217 lock = Lock()
2218 for i in range(10):
2219 Process(target=f, args=(lock,)).start()
2220
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002221Beware of replacing :data:`sys.stdin` with a "file like object"
Jesse Noller1b90efb2009-06-30 17:11:52 +00002222
2223 :mod:`multiprocessing` originally unconditionally called::
2224
2225 os.close(sys.stdin.fileno())
2226
R. David Murray321afa82009-07-01 02:49:10 +00002227 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
Jesse Noller1b90efb2009-06-30 17:11:52 +00002228 in issues with processes-in-processes. This has been changed to::
2229
2230 sys.stdin.close()
2231 sys.stdin = open(os.devnull)
2232
2233 Which solves the fundamental issue of processes colliding with each other
2234 resulting in a bad file descriptor error, but introduces a potential danger
2235 to applications which replace :func:`sys.stdin` with a "file-like object"
R. David Murray321afa82009-07-01 02:49:10 +00002236 with output buffering. This danger is that if multiple processes call
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002237 :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
Jesse Noller1b90efb2009-06-30 17:11:52 +00002238 data being flushed to the object multiple times, resulting in corruption.
2239
2240 If you write a file-like object and implement your own caching, you can
2241 make it fork-safe by storing the pid whenever you append to the cache,
2242 and discarding the cache when the pid changes. For example::
2243
2244 @property
2245 def cache(self):
2246 pid = os.getpid()
2247 if pid != self._pid:
2248 self._pid = pid
2249 self._cache = []
2250 return self._cache
2251
2252 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002253
2254Windows
2255~~~~~~~
2256
2257Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2258
2259More picklability
2260
2261 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2262 means, in particular, that bound or unbound methods cannot be used directly
2263 as the ``target`` argument on Windows --- just define a function and use
2264 that instead.
2265
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002266 Also, if you subclass :class:`~multiprocessing.Process` then make sure that
2267 instances will be picklable when the :meth:`Process.start
2268 <multiprocessing.Process.start>` method is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002269
2270Global variables
2271
2272 Bear in mind that if code run in a child process tries to access a global
2273 variable, then the value it sees (if any) may not be the same as the value
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002274 in the parent process at the time that :meth:`Process.start
2275 <multiprocessing.Process.start>` was called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002276
2277 However, global variables which are just module level constants cause no
2278 problems.
2279
2280Safe importing of main module
2281
2282 Make sure that the main module can be safely imported by a new Python
2283 interpreter without causing unintended side effects (such a starting a new
2284 process).
2285
2286 For example, under Windows running the following module would fail with a
2287 :exc:`RuntimeError`::
2288
2289 from multiprocessing import Process
2290
2291 def foo():
2292 print 'hello'
2293
2294 p = Process(target=foo)
2295 p.start()
2296
2297 Instead one should protect the "entry point" of the program by using ``if
2298 __name__ == '__main__':`` as follows::
2299
2300 from multiprocessing import Process, freeze_support
2301
2302 def foo():
2303 print 'hello'
2304
2305 if __name__ == '__main__':
2306 freeze_support()
2307 p = Process(target=foo)
2308 p.start()
2309
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002310 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002311 normally instead of frozen.)
2312
2313 This allows the newly spawned Python interpreter to safely import the module
2314 and then run the module's ``foo()`` function.
2315
2316 Similar restrictions apply if a pool or manager is created in the main
2317 module.
2318
2319
2320.. _multiprocessing-examples:
2321
2322Examples
2323--------
2324
2325Demonstration of how to create and use customized managers and proxies:
2326
2327.. literalinclude:: ../includes/mp_newtype.py
2328
2329
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002330Using :class:`~multiprocessing.pool.Pool`:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002331
2332.. literalinclude:: ../includes/mp_pool.py
2333
2334
2335Synchronization types like locks, conditions and queues:
2336
2337.. literalinclude:: ../includes/mp_synchronize.py
2338
2339
Georg Brandl21946af2010-10-06 09:28:45 +00002340An example showing how to use queues to feed tasks to a collection of worker
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002341processes and collect the results:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002342
2343.. literalinclude:: ../includes/mp_workers.py
2344
2345
2346An example of how a pool of worker processes can each run a
2347:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2348socket.
2349
2350.. literalinclude:: ../includes/mp_webserver.py
2351
2352
2353Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2354
2355.. literalinclude:: ../includes/mp_benchmarks.py
2356