blob: 021e3c8e18fb467f27adf143b1f3fc571355e4c1 [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
163
164Sharing state between processes
165~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166
167As mentioned above, when doing concurrent programming it is usually best to
168avoid using shared state as far as possible. This is particularly true when
169using multiple processes.
170
171However, if you really do need to use some shared data then
172:mod:`multiprocessing` provides a couple of ways of doing so.
173
174**Shared memory**
175
176 Data can be stored in a shared memory map using :class:`Value` or
177 :class:`Array`. For example, the following code ::
178
179 from multiprocessing import Process, Value, Array
180
181 def f(n, a):
182 n.value = 3.1415927
183 for i in range(len(a)):
184 a[i] = -a[i]
185
186 if __name__ == '__main__':
187 num = Value('d', 0.0)
188 arr = Array('i', range(10))
189
190 p = Process(target=f, args=(num, arr))
191 p.start()
192 p.join()
193
194 print num.value
195 print arr[:]
196
197 will print ::
198
199 3.1415927
200 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
201
202 The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
203 typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
Benjamin Peterson90f36732008-07-12 20:16:19 +0000204 double precision float and ``'i'`` indicates a signed integer. These shared
Georg Brandl837fbb02010-11-26 07:58:55 +0000205 objects will be process and thread-safe.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000206
207 For more flexibility in using shared memory one can use the
208 :mod:`multiprocessing.sharedctypes` module which supports the creation of
209 arbitrary ctypes objects allocated from shared memory.
210
211**Server process**
212
213 A manager object returned by :func:`Manager` controls a server process which
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000214 holds Python objects and allows other processes to manipulate them using
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000215 proxies.
216
217 A manager returned by :func:`Manager` will support types :class:`list`,
218 :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`,
219 :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
Sandro Tosi8b48c662012-02-25 19:35:16 +0100220 :class:`Event`, :class:`~multiprocessing.Queue`, :class:`Value` and :class:`Array`. For
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000221 example, ::
222
223 from multiprocessing import Process, Manager
224
225 def f(d, l):
226 d[1] = '1'
227 d['2'] = 2
228 d[0.25] = None
229 l.reverse()
230
231 if __name__ == '__main__':
232 manager = Manager()
233
234 d = manager.dict()
235 l = manager.list(range(10))
236
237 p = Process(target=f, args=(d, l))
238 p.start()
239 p.join()
240
241 print d
242 print l
243
244 will print ::
245
246 {0.25: None, 1: '1', '2': 2}
247 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
248
249 Server process managers are more flexible than using shared memory objects
250 because they can be made to support arbitrary object types. Also, a single
251 manager can be shared by processes on different computers over a network.
252 They are, however, slower than using shared memory.
253
254
255Using a pool of workers
256~~~~~~~~~~~~~~~~~~~~~~~
257
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000258The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000259processes. It has methods which allows tasks to be offloaded to the worker
260processes in a few different ways.
261
262For example::
263
264 from multiprocessing import Pool
265
266 def f(x):
267 return x*x
268
269 if __name__ == '__main__':
270 pool = Pool(processes=4) # start 4 worker processes
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200271 result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000272 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
273 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
274
Richard Oudkerk49032532013-07-02 12:31:50 +0100275Note that the methods of a pool should only ever be used by the
276process which created it.
277
Antoine Pitroua8efb6b2015-01-11 15:09:27 +0100278.. note::
279
280 Functionality within this package requires that the ``__main__`` module be
281 importable by the children. This is covered in :ref:`multiprocessing-programming`
282 however it is worth pointing out here. This means that some examples, such
283 as the :class:`Pool` examples will not work in the interactive interpreter.
284 For example::
285
286 >>> from multiprocessing import Pool
287 >>> p = Pool(5)
288 >>> def f(x):
289 ... return x*x
290 ...
291 >>> p.map(f, [1,2,3])
292 Process PoolWorker-1:
293 Process PoolWorker-2:
294 Process PoolWorker-3:
295 Traceback (most recent call last):
296 Traceback (most recent call last):
297 Traceback (most recent call last):
298 AttributeError: 'module' object has no attribute 'f'
299 AttributeError: 'module' object has no attribute 'f'
300 AttributeError: 'module' object has no attribute 'f'
301
302 (If you try this it will actually output three full tracebacks
303 interleaved in a semi-random fashion, and then you may have to
304 stop the master process somehow.)
305
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000306
307Reference
308---------
309
310The :mod:`multiprocessing` package mostly replicates the API of the
311:mod:`threading` module.
312
313
314:class:`Process` and exceptions
315~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
316
Ezio Melottied3f5902012-09-14 06:48:32 +0300317.. class:: Process(group=None, target=None, name=None, args=(), kwargs={})
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000318
319 Process objects represent activity that is run in a separate process. The
320 :class:`Process` class has equivalents of all the methods of
321 :class:`threading.Thread`.
322
323 The constructor should always be called with keyword arguments. *group*
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000324 should always be ``None``; it exists solely for compatibility with
Benjamin Peterson73641d72008-08-20 14:07:59 +0000325 :class:`threading.Thread`. *target* is the callable object to be invoked by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000326 the :meth:`run()` method. It defaults to ``None``, meaning nothing is
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000327 called. *name* is the process name. By default, a unique name is constructed
328 of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\
329 :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
330 is determined by the *generation* of the process. *args* is the argument
331 tuple for the target invocation. *kwargs* is a dictionary of keyword
332 arguments for the target invocation. By default, no arguments are passed to
333 *target*.
334
335 If a subclass overrides the constructor, it must make sure it invokes the
336 base class constructor (:meth:`Process.__init__`) before doing anything else
337 to the process.
338
339 .. method:: run()
340
341 Method representing the process's activity.
342
343 You may override this method in a subclass. The standard :meth:`run`
344 method invokes the callable object passed to the object's constructor as
345 the target argument, if any, with sequential and keyword arguments taken
346 from the *args* and *kwargs* arguments, respectively.
347
348 .. method:: start()
349
350 Start the process's activity.
351
352 This must be called at most once per process object. It arranges for the
353 object's :meth:`run` method to be invoked in a separate process.
354
355 .. method:: join([timeout])
356
357 Block the calling thread until the process whose :meth:`join` method is
358 called terminates or until the optional timeout occurs.
359
360 If *timeout* is ``None`` then there is no timeout.
361
362 A process can be joined many times.
363
364 A process cannot join itself because this would cause a deadlock. It is
365 an error to attempt to join a process before it has been started.
366
Benjamin Peterson73641d72008-08-20 14:07:59 +0000367 .. attribute:: name
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000368
Benjamin Peterson73641d72008-08-20 14:07:59 +0000369 The process's name.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000370
371 The name is a string used for identification purposes only. It has no
372 semantics. Multiple processes may be given the same name. The initial
373 name is set by the constructor.
374
Jesse Nollera280fd72008-11-28 18:22:54 +0000375 .. method:: is_alive
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000376
377 Return whether the process is alive.
378
379 Roughly, a process object is alive from the moment the :meth:`start`
380 method returns until the child process terminates.
381
Benjamin Peterson73641d72008-08-20 14:07:59 +0000382 .. attribute:: daemon
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000383
Georg Brandl3bcb0ce2008-12-30 10:15:49 +0000384 The process's daemon flag, a Boolean value. This must be set before
Benjamin Peterson73641d72008-08-20 14:07:59 +0000385 :meth:`start` is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000386
387 The initial value is inherited from the creating process.
388
389 When a process exits, it attempts to terminate all of its daemonic child
390 processes.
391
392 Note that a daemonic process is not allowed to create child processes.
393 Otherwise a daemonic process would leave its children orphaned if it gets
Jesse Nollerd4792cd2009-06-29 18:20:34 +0000394 terminated when its parent process exits. Additionally, these are **not**
395 Unix daemons or services, they are normal processes that will be
Georg Brandl09302282010-10-06 09:32:48 +0000396 terminated (and not joined) if non-daemonic processes have exited.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000397
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300398 In addition to the :class:`threading.Thread` API, :class:`Process` objects
Brett Cannon971f1022008-08-24 23:15:19 +0000399 also support the following attributes and methods:
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000400
Benjamin Peterson73641d72008-08-20 14:07:59 +0000401 .. attribute:: pid
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000402
403 Return the process ID. Before the process is spawned, this will be
404 ``None``.
405
Benjamin Peterson73641d72008-08-20 14:07:59 +0000406 .. attribute:: exitcode
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000407
Benjamin Peterson73641d72008-08-20 14:07:59 +0000408 The child's exit code. This will be ``None`` if the process has not yet
409 terminated. A negative value *-N* indicates that the child was terminated
410 by signal *N*.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000411
Benjamin Peterson73641d72008-08-20 14:07:59 +0000412 .. attribute:: authkey
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000413
Benjamin Peterson73641d72008-08-20 14:07:59 +0000414 The process's authentication key (a byte string).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000415
416 When :mod:`multiprocessing` is initialized the main process is assigned a
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300417 random string using :func:`os.urandom`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000418
419 When a :class:`Process` object is created, it will inherit the
Benjamin Peterson73641d72008-08-20 14:07:59 +0000420 authentication key of its parent process, although this may be changed by
421 setting :attr:`authkey` to another byte string.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000422
423 See :ref:`multiprocessing-auth-keys`.
424
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000425 .. method:: terminate()
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000426
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000427 Terminate the process. On Unix this is done using the ``SIGTERM`` signal;
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100428 on Windows :c:func:`TerminateProcess` is used. Note that exit handlers and
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000429 finally clauses, etc., will not be executed.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000430
431 Note that descendant processes of the process will *not* be terminated --
432 they will simply become orphaned.
433
434 .. warning::
435
436 If this method is used when the associated process is using a pipe or
437 queue then the pipe or queue is liable to become corrupted and may
438 become unusable by other process. Similarly, if the process has
439 acquired a lock or semaphore etc. then terminating it is liable to
440 cause other processes to deadlock.
441
Richard Oudkerkacfbe222013-06-24 15:41:36 +0100442 Note that the :meth:`start`, :meth:`join`, :meth:`is_alive`,
443 :meth:`terminate` and :attr:`exitcode` methods should only be called by
444 the process that created the process object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000445
R. David Murray636b23a2009-04-28 16:08:18 +0000446 Example usage of some of the methods of :class:`Process`:
447
448 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000449
Georg Brandl19cc9442008-10-16 21:36:39 +0000450 >>> import multiprocessing, time, signal
451 >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000452 >>> print p, p.is_alive()
453 <Process(Process-1, initial)> False
454 >>> p.start()
455 >>> print p, p.is_alive()
456 <Process(Process-1, started)> True
457 >>> p.terminate()
R. David Murray636b23a2009-04-28 16:08:18 +0000458 >>> time.sleep(0.1)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000459 >>> print p, p.is_alive()
460 <Process(Process-1, stopped[SIGTERM])> False
Benjamin Peterson73641d72008-08-20 14:07:59 +0000461 >>> p.exitcode == -signal.SIGTERM
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000462 True
463
464
465.. exception:: BufferTooShort
466
467 Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
468 buffer object is too small for the message read.
469
470 If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
471 the message as a byte string.
472
473
474Pipes and Queues
475~~~~~~~~~~~~~~~~
476
477When using multiple processes, one generally uses message passing for
478communication between processes and avoids having to use any synchronization
479primitives like locks.
480
481For passing messages one can use :func:`Pipe` (for a connection between two
482processes) or a queue (which allows multiple producers and consumers).
483
Sandro Tosi8b48c662012-02-25 19:35:16 +0100484The :class:`~multiprocessing.Queue`, :class:`multiprocessing.queues.SimpleQueue` and :class:`JoinableQueue` types are multi-producer,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000485multi-consumer FIFO queues modelled on the :class:`Queue.Queue` class in the
Sandro Tosi8b48c662012-02-25 19:35:16 +0100486standard library. They differ in that :class:`~multiprocessing.Queue` lacks the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000487:meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join` methods introduced
488into Python 2.5's :class:`Queue.Queue` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000489
490If you use :class:`JoinableQueue` then you **must** call
491:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200492semaphore used to count the number of unfinished tasks may eventually overflow,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000493raising an exception.
494
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000495Note that one can also create a shared queue by using a manager object -- see
496:ref:`multiprocessing-managers`.
497
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000498.. note::
499
500 :mod:`multiprocessing` uses the usual :exc:`Queue.Empty` and
501 :exc:`Queue.Full` exceptions to signal a timeout. They are not available in
502 the :mod:`multiprocessing` namespace so you need to import them from
503 :mod:`Queue`.
504
Richard Oudkerk56e968c2013-06-24 14:45:24 +0100505.. note::
506
507 When an object is put on a queue, the object is pickled and a
508 background thread later flushes the pickled data to an underlying
509 pipe. This has some consequences which are a little surprising,
Richard Oudkerk2cc73e82013-06-24 18:11:21 +0100510 but should not cause any practical difficulties -- if they really
511 bother you then you can instead use a queue created with a
512 :ref:`manager <multiprocessing-managers>`.
Richard Oudkerk56e968c2013-06-24 14:45:24 +0100513
514 (1) After putting an object on an empty queue there may be an
Richard Oudkerk66e0a042013-06-24 20:38:22 +0100515 infinitesimal delay before the queue's :meth:`~Queue.empty`
Richard Oudkerk56e968c2013-06-24 14:45:24 +0100516 method returns :const:`False` and :meth:`~Queue.get_nowait` can
517 return without raising :exc:`Queue.Empty`.
518
519 (2) If multiple processes are enqueuing objects, it is possible for
520 the objects to be received at the other end out-of-order.
521 However, objects enqueued by the same process will always be in
522 the expected order with respect to each other.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000523
524.. warning::
525
526 If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
Sandro Tosi8b48c662012-02-25 19:35:16 +0100527 while it is trying to use a :class:`~multiprocessing.Queue`, then the data in the queue is
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200528 likely to become corrupted. This may cause any other process to get an
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000529 exception when it tries to use the queue later on.
530
531.. warning::
532
533 As mentioned above, if a child process has put items on a queue (and it has
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300534 not used :meth:`JoinableQueue.cancel_join_thread
535 <multiprocessing.Queue.cancel_join_thread>`), then that process will
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000536 not terminate until all buffered items have been flushed to the pipe.
537
538 This means that if you try joining that process you may get a deadlock unless
539 you are sure that all items which have been put on the queue have been
540 consumed. Similarly, if the child process is non-daemonic then the parent
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000541 process may hang on exit when it tries to join all its non-daemonic children.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000542
543 Note that a queue created using a manager does not have this issue. See
544 :ref:`multiprocessing-programming`.
545
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000546For an example of the usage of queues for interprocess communication see
547:ref:`multiprocessing-examples`.
548
549
550.. function:: Pipe([duplex])
551
552 Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing
553 the ends of a pipe.
554
555 If *duplex* is ``True`` (the default) then the pipe is bidirectional. If
556 *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
557 used for receiving messages and ``conn2`` can only be used for sending
558 messages.
559
560
561.. class:: Queue([maxsize])
562
563 Returns a process shared queue implemented using a pipe and a few
564 locks/semaphores. When a process first puts an item on the queue a feeder
565 thread is started which transfers objects from a buffer into the pipe.
566
567 The usual :exc:`Queue.Empty` and :exc:`Queue.Full` exceptions from the
568 standard library's :mod:`Queue` module are raised to signal timeouts.
569
Sandro Tosi8b48c662012-02-25 19:35:16 +0100570 :class:`~multiprocessing.Queue` implements all the methods of :class:`Queue.Queue` except for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000571 :meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000572
573 .. method:: qsize()
574
575 Return the approximate size of the queue. Because of
576 multithreading/multiprocessing semantics, this number is not reliable.
577
578 Note that this may raise :exc:`NotImplementedError` on Unix platforms like
Georg Brandl9af94982008-09-13 17:41:16 +0000579 Mac OS X where ``sem_getvalue()`` is not implemented.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000580
581 .. method:: empty()
582
583 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
584 multithreading/multiprocessing semantics, this is not reliable.
585
586 .. method:: full()
587
588 Return ``True`` if the queue is full, ``False`` otherwise. Because of
589 multithreading/multiprocessing semantics, this is not reliable.
590
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800591 .. method:: put(obj[, block[, timeout]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000592
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800593 Put obj into the queue. If the optional argument *block* is ``True``
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000594 (the default) and *timeout* is ``None`` (the default), block if necessary until
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000595 a free slot is available. If *timeout* is a positive number, it blocks at
596 most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
597 free slot was available within that time. Otherwise (*block* is
598 ``False``), put an item on the queue if a free slot is immediately
599 available, else raise the :exc:`Queue.Full` exception (*timeout* is
600 ignored in that case).
601
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800602 .. method:: put_nowait(obj)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000603
Senthil Kumaran9541f8e2011-09-06 00:23:10 +0800604 Equivalent to ``put(obj, False)``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000605
606 .. method:: get([block[, timeout]])
607
608 Remove and return an item from the queue. If optional args *block* is
609 ``True`` (the default) and *timeout* is ``None`` (the default), block if
610 necessary until an item is available. If *timeout* is a positive number,
611 it blocks at most *timeout* seconds and raises the :exc:`Queue.Empty`
612 exception if no item was available within that time. Otherwise (block is
613 ``False``), return an item if one is immediately available, else raise the
614 :exc:`Queue.Empty` exception (*timeout* is ignored in that case).
615
616 .. method:: get_nowait()
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000617
618 Equivalent to ``get(False)``.
619
Sandro Tosi8b48c662012-02-25 19:35:16 +0100620 :class:`~multiprocessing.Queue` has a few additional methods not found in
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000621 :class:`Queue.Queue`. These methods are usually unnecessary for most
622 code:
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000623
624 .. method:: close()
625
626 Indicate that no more data will be put on this queue by the current
627 process. The background thread will quit once it has flushed all buffered
628 data to the pipe. This is called automatically when the queue is garbage
629 collected.
630
631 .. method:: join_thread()
632
633 Join the background thread. This can only be used after :meth:`close` has
634 been called. It blocks until the background thread exits, ensuring that
635 all data in the buffer has been flushed to the pipe.
636
637 By default if a process is not the creator of the queue then on exit it
638 will attempt to join the queue's background thread. The process can call
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000639 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000640
641 .. method:: cancel_join_thread()
642
643 Prevent :meth:`join_thread` from blocking. In particular, this prevents
644 the background thread from being joined automatically when the process
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000645 exits -- see :meth:`join_thread`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000646
Richard Oudkerk4bc130c2013-07-02 12:58:21 +0100647 A better name for this method might be
648 ``allow_exit_without_flush()``. It is likely to cause enqueued
649 data to lost, and you almost certainly will not need to use it.
650 It is really only there if you need the current process to exit
651 immediately without waiting to flush enqueued data to the
652 underlying pipe, and you don't care about lost data.
653
Berker Peksag928b3ff2015-04-08 18:12:53 +0300654 .. note::
655
656 This class's functionality requires a functioning shared semaphore
657 implementation on the host operating system. Without one, the
658 functionality in this class will be disabled, and attempts to
659 instantiate a :class:`Queue` will result in an :exc:`ImportError`. See
660 :issue:`3770` for additional information. The same holds true for any
661 of the specialized queue types listed below.
662
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000663
Sandro Tosic0b11722012-02-15 22:39:52 +0100664.. class:: multiprocessing.queues.SimpleQueue()
665
Sandro Tosi8b48c662012-02-25 19:35:16 +0100666 It is a simplified :class:`~multiprocessing.Queue` type, very close to a locked :class:`Pipe`.
Sandro Tosic0b11722012-02-15 22:39:52 +0100667
668 .. method:: empty()
669
670 Return ``True`` if the queue is empty, ``False`` otherwise.
671
672 .. method:: get()
673
674 Remove and return an item from the queue.
675
676 .. method:: put(item)
677
678 Put *item* into the queue.
679
680
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000681.. class:: JoinableQueue([maxsize])
682
Sandro Tosi8b48c662012-02-25 19:35:16 +0100683 :class:`JoinableQueue`, a :class:`~multiprocessing.Queue` subclass, is a queue which
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000684 additionally has :meth:`task_done` and :meth:`join` methods.
685
686 .. method:: task_done()
687
688 Indicate that a formerly enqueued task is complete. Used by queue consumer
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000689 threads. For each :meth:`~Queue.get` used to fetch a task, a subsequent
690 call to :meth:`task_done` tells the queue that the processing on the task
691 is complete.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000692
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300693 If a :meth:`~Queue.Queue.join` is currently blocking, it will resume when all
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000694 items have been processed (meaning that a :meth:`task_done` call was
695 received for every item that had been :meth:`~Queue.put` into the queue).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000696
697 Raises a :exc:`ValueError` if called more times than there were items
698 placed in the queue.
699
700
701 .. method:: join()
702
703 Block until all items in the queue have been gotten and processed.
704
705 The count of unfinished tasks goes up whenever an item is added to the
706 queue. The count goes down whenever a consumer thread calls
707 :meth:`task_done` to indicate that the item was retrieved and all work on
708 it is complete. When the count of unfinished tasks drops to zero,
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300709 :meth:`~Queue.Queue.join` unblocks.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000710
711
712Miscellaneous
713~~~~~~~~~~~~~
714
715.. function:: active_children()
716
717 Return list of all live children of the current process.
718
Zachary Ware06b74a72014-10-03 10:55:12 -0500719 Calling this has the side effect of "joining" any processes which have
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000720 already finished.
721
722.. function:: cpu_count()
723
724 Return the number of CPUs in the system. May raise
725 :exc:`NotImplementedError`.
726
727.. function:: current_process()
728
729 Return the :class:`Process` object corresponding to the current process.
730
731 An analogue of :func:`threading.current_thread`.
732
733.. function:: freeze_support()
734
735 Add support for when a program which uses :mod:`multiprocessing` has been
736 frozen to produce a Windows executable. (Has been tested with **py2exe**,
737 **PyInstaller** and **cx_Freeze**.)
738
739 One needs to call this function straight after the ``if __name__ ==
740 '__main__'`` line of the main module. For example::
741
742 from multiprocessing import Process, freeze_support
743
744 def f():
745 print 'hello world!'
746
747 if __name__ == '__main__':
748 freeze_support()
749 Process(target=f).start()
750
R. David Murray636b23a2009-04-28 16:08:18 +0000751 If the ``freeze_support()`` line is omitted then trying to run the frozen
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000752 executable will raise :exc:`RuntimeError`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000753
754 If the module is being run normally by the Python interpreter then
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000755 :func:`freeze_support` has no effect.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000756
757.. function:: set_executable()
758
Ezio Melotti062d2b52009-12-19 22:41:49 +0000759 Sets the path of the Python interpreter to use when starting a child process.
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000760 (By default :data:`sys.executable` is used). Embedders will probably need to
761 do some thing like ::
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000762
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200763 set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000764
R. David Murray636b23a2009-04-28 16:08:18 +0000765 before they can create child processes. (Windows only)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000766
767
768.. note::
769
770 :mod:`multiprocessing` contains no analogues of
771 :func:`threading.active_count`, :func:`threading.enumerate`,
772 :func:`threading.settrace`, :func:`threading.setprofile`,
773 :class:`threading.Timer`, or :class:`threading.local`.
774
775
776Connection Objects
777~~~~~~~~~~~~~~~~~~
778
779Connection objects allow the sending and receiving of picklable objects or
780strings. They can be thought of as message oriented connected sockets.
781
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200782Connection objects are usually created using :func:`Pipe` -- see also
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000783:ref:`multiprocessing-listeners-clients`.
784
785.. class:: Connection
786
787 .. method:: send(obj)
788
789 Send an object to the other end of the connection which should be read
790 using :meth:`recv`.
791
Jesse Noller5053fbb2009-04-02 04:22:09 +0000792 The object must be picklable. Very large pickles (approximately 32 MB+,
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200793 though it depends on the OS) may raise a :exc:`ValueError` exception.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000794
795 .. method:: recv()
796
797 Return an object sent from the other end of the connection using
Sandro Tosif788cf72012-01-07 17:56:43 +0100798 :meth:`send`. Blocks until there its something to receive. Raises
799 :exc:`EOFError` if there is nothing left to receive
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000800 and the other end was closed.
801
802 .. method:: fileno()
803
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200804 Return the file descriptor or handle used by the connection.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000805
806 .. method:: close()
807
808 Close the connection.
809
810 This is called automatically when the connection is garbage collected.
811
812 .. method:: poll([timeout])
813
814 Return whether there is any data available to be read.
815
816 If *timeout* is not specified then it will return immediately. If
817 *timeout* is a number then this specifies the maximum time in seconds to
818 block. If *timeout* is ``None`` then an infinite timeout is used.
819
820 .. method:: send_bytes(buffer[, offset[, size]])
821
822 Send byte data from an object supporting the buffer interface as a
823 complete message.
824
825 If *offset* is given then data is read from that position in *buffer*. If
Jesse Noller5053fbb2009-04-02 04:22:09 +0000826 *size* is given then that many bytes will be read from buffer. Very large
827 buffers (approximately 32 MB+, though it depends on the OS) may raise a
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200828 :exc:`ValueError` exception
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000829
830 .. method:: recv_bytes([maxlength])
831
832 Return a complete message of byte data sent from the other end of the
Sandro Tosif788cf72012-01-07 17:56:43 +0100833 connection as a string. Blocks until there is something to receive.
834 Raises :exc:`EOFError` if there is nothing left
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000835 to receive and the other end has closed.
836
837 If *maxlength* is specified and the message is longer than *maxlength*
838 then :exc:`IOError` is raised and the connection will no longer be
839 readable.
840
841 .. method:: recv_bytes_into(buffer[, offset])
842
843 Read into *buffer* a complete message of byte data sent from the other end
Sandro Tosif788cf72012-01-07 17:56:43 +0100844 of the connection and return the number of bytes in the message. Blocks
845 until there is something to receive. Raises
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000846 :exc:`EOFError` if there is nothing left to receive and the other end was
847 closed.
848
849 *buffer* must be an object satisfying the writable buffer interface. If
850 *offset* is given then the message will be written into the buffer from
R. David Murray636b23a2009-04-28 16:08:18 +0000851 that position. Offset must be a non-negative integer less than the
852 length of *buffer* (in bytes).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000853
854 If the buffer is too short then a :exc:`BufferTooShort` exception is
855 raised and the complete message is available as ``e.args[0]`` where ``e``
856 is the exception instance.
857
858
859For example:
860
R. David Murray636b23a2009-04-28 16:08:18 +0000861.. doctest::
862
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000863 >>> from multiprocessing import Pipe
864 >>> a, b = Pipe()
865 >>> a.send([1, 'hello', None])
866 >>> b.recv()
867 [1, 'hello', None]
868 >>> b.send_bytes('thank you')
869 >>> a.recv_bytes()
870 'thank you'
871 >>> import array
872 >>> arr1 = array.array('i', range(5))
873 >>> arr2 = array.array('i', [0] * 10)
874 >>> a.send_bytes(arr1)
875 >>> count = b.recv_bytes_into(arr2)
876 >>> assert count == len(arr1) * arr1.itemsize
877 >>> arr2
878 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
879
880
881.. warning::
882
883 The :meth:`Connection.recv` method automatically unpickles the data it
884 receives, which can be a security risk unless you can trust the process
885 which sent the message.
886
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000887 Therefore, unless the connection object was produced using :func:`Pipe` you
888 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
889 methods after performing some sort of authentication. See
890 :ref:`multiprocessing-auth-keys`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000891
892.. warning::
893
894 If a process is killed while it is trying to read or write to a pipe then
895 the data in the pipe is likely to become corrupted, because it may become
896 impossible to be sure where the message boundaries lie.
897
898
899Synchronization primitives
900~~~~~~~~~~~~~~~~~~~~~~~~~~
901
902Generally synchronization primitives are not as necessary in a multiprocess
Andrew M. Kuchling8ea605c2008-07-14 01:18:16 +0000903program as they are in a multithreaded program. See the documentation for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000904:mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000905
906Note that one can also create synchronization primitives by using a manager
907object -- see :ref:`multiprocessing-managers`.
908
909.. class:: BoundedSemaphore([value])
910
911 A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`.
912
Georg Brandl042d6a42010-05-21 21:47:05 +0000913 (On Mac OS X, this is indistinguishable from :class:`Semaphore` because
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000914 ``sem_getvalue()`` is not implemented on that platform).
915
916.. class:: Condition([lock])
917
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000918 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000919
920 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
921 object from :mod:`multiprocessing`.
922
923.. class:: Event()
924
925 A clone of :class:`threading.Event`.
Jesse Noller02cb0eb2009-04-01 03:45:50 +0000926 This method returns the state of the internal semaphore on exit, so it
927 will always return ``True`` except if a timeout is given and the operation
928 times out.
929
930 .. versionchanged:: 2.7
931 Previously, the method always returned ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000932
933.. class:: Lock()
934
935 A non-recursive lock object: a clone of :class:`threading.Lock`.
936
937.. class:: RLock()
938
939 A recursive lock object: a clone of :class:`threading.RLock`.
940
941.. class:: Semaphore([value])
942
Ross Lagerwalla3ed3f02011-03-14 10:43:36 +0200943 A semaphore object: a clone of :class:`threading.Semaphore`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000944
945.. note::
946
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000947 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000948 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
949 by the equivalents in :mod:`threading`. The signature is
950 ``acquire(block=True, timeout=None)`` with keyword parameters being
951 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
952 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
953 ignored.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000954
Georg Brandl042d6a42010-05-21 21:47:05 +0000955 On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
956 a timeout will emulate that function's behavior using a sleeping loop.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000957
958.. note::
959
960 If the SIGINT signal generated by Ctrl-C arrives while the main thread is
961 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
962 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
963 or :meth:`Condition.wait` then the call will be immediately interrupted and
964 :exc:`KeyboardInterrupt` will be raised.
965
966 This differs from the behaviour of :mod:`threading` where SIGINT will be
967 ignored while the equivalent blocking calls are in progress.
968
Berker Peksag928b3ff2015-04-08 18:12:53 +0300969.. note::
970
971 Some of this package's functionality requires a functioning shared semaphore
972 implementation on the host operating system. Without one, the
973 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
974 import it will result in an :exc:`ImportError`. See
975 :issue:`3770` for additional information.
976
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000977
978Shared :mod:`ctypes` Objects
979~~~~~~~~~~~~~~~~~~~~~~~~~~~~
980
981It is possible to create shared objects using shared memory which can be
982inherited by child processes.
983
Jesse Noller6ab22152009-01-18 02:45:38 +0000984.. function:: Value(typecode_or_type, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000985
986 Return a :mod:`ctypes` object allocated from shared memory. By default the
987 return value is actually a synchronized wrapper for the object.
988
989 *typecode_or_type* determines the type of the returned object: it is either a
990 ctypes type or a one character typecode of the kind used by the :mod:`array`
991 module. *\*args* is passed on to the constructor for the type.
992
Richard Oudkerka69712c2013-11-17 17:00:38 +0000993 If *lock* is ``True`` (the default) then a new recursive lock
994 object is created to synchronize access to the value. If *lock* is
995 a :class:`Lock` or :class:`RLock` object then that will be used to
996 synchronize access to the value. If *lock* is ``False`` then
997 access to the returned object will not be automatically protected
998 by a lock, so it will not necessarily be "process-safe".
999
1000 Operations like ``+=`` which involve a read and write are not
1001 atomic. So if, for instance, you want to atomically increment a
1002 shared value it is insufficient to just do ::
1003
1004 counter.value += 1
1005
1006 Assuming the associated lock is recursive (which it is by default)
1007 you can instead do ::
1008
1009 with counter.get_lock():
1010 counter.value += 1
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001011
1012 Note that *lock* is a keyword-only argument.
1013
1014.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
1015
1016 Return a ctypes array allocated from shared memory. By default the return
1017 value is actually a synchronized wrapper for the array.
1018
1019 *typecode_or_type* determines the type of the elements of the returned array:
1020 it is either a ctypes type or a one character typecode of the kind used by
1021 the :mod:`array` module. If *size_or_initializer* is an integer, then it
1022 determines the length of the array, and the array will be initially zeroed.
1023 Otherwise, *size_or_initializer* is a sequence which is used to initialize
1024 the array and whose length determines the length of the array.
1025
1026 If *lock* is ``True`` (the default) then a new lock object is created to
1027 synchronize access to the value. If *lock* is a :class:`Lock` or
1028 :class:`RLock` object then that will be used to synchronize access to the
1029 value. If *lock* is ``False`` then access to the returned object will not be
1030 automatically protected by a lock, so it will not necessarily be
1031 "process-safe".
1032
1033 Note that *lock* is a keyword only argument.
1034
Georg Brandlb053f992008-11-22 08:34:14 +00001035 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001036 attributes which allow one to use it to store and retrieve strings.
1037
1038
1039The :mod:`multiprocessing.sharedctypes` module
1040>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1041
1042.. module:: multiprocessing.sharedctypes
1043 :synopsis: Allocate ctypes objects from shared memory.
1044
1045The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
1046:mod:`ctypes` objects from shared memory which can be inherited by child
1047processes.
1048
1049.. note::
1050
Benjamin Peterson90f36732008-07-12 20:16:19 +00001051 Although it is possible to store a pointer in shared memory remember that
1052 this will refer to a location in the address space of a specific process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001053 However, the pointer is quite likely to be invalid in the context of a second
1054 process and trying to dereference the pointer from the second process may
1055 cause a crash.
1056
1057.. function:: RawArray(typecode_or_type, size_or_initializer)
1058
1059 Return a ctypes array allocated from shared memory.
1060
1061 *typecode_or_type* determines the type of the elements of the returned array:
1062 it is either a ctypes type or a one character typecode of the kind used by
1063 the :mod:`array` module. If *size_or_initializer* is an integer then it
1064 determines the length of the array, and the array will be initially zeroed.
1065 Otherwise *size_or_initializer* is a sequence which is used to initialize the
1066 array and whose length determines the length of the array.
1067
1068 Note that setting and getting an element is potentially non-atomic -- use
1069 :func:`Array` instead to make sure that access is automatically synchronized
1070 using a lock.
1071
1072.. function:: RawValue(typecode_or_type, *args)
1073
1074 Return a ctypes object allocated from shared memory.
1075
1076 *typecode_or_type* determines the type of the returned object: it is either a
1077 ctypes type or a one character typecode of the kind used by the :mod:`array`
Jesse Noller6ab22152009-01-18 02:45:38 +00001078 module. *\*args* is passed on to the constructor for the type.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001079
1080 Note that setting and getting the value is potentially non-atomic -- use
1081 :func:`Value` instead to make sure that access is automatically synchronized
1082 using a lock.
1083
Georg Brandlb053f992008-11-22 08:34:14 +00001084 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001085 attributes which allow one to use it to store and retrieve strings -- see
1086 documentation for :mod:`ctypes`.
1087
Jesse Noller6ab22152009-01-18 02:45:38 +00001088.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001089
1090 The same as :func:`RawArray` except that depending on the value of *lock* a
1091 process-safe synchronization wrapper may be returned instead of a raw ctypes
1092 array.
1093
1094 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001095 synchronize access to the value. If *lock* is a
1096 :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
1097 then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001098 value. If *lock* is ``False`` then access to the returned object will not be
1099 automatically protected by a lock, so it will not necessarily be
1100 "process-safe".
1101
1102 Note that *lock* is a keyword-only argument.
1103
1104.. function:: Value(typecode_or_type, *args[, lock])
1105
1106 The same as :func:`RawValue` except that depending on the value of *lock* a
1107 process-safe synchronization wrapper may be returned instead of a raw ctypes
1108 object.
1109
1110 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001111 synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or
1112 :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001113 value. If *lock* is ``False`` then access to the returned object will not be
1114 automatically protected by a lock, so it will not necessarily be
1115 "process-safe".
1116
1117 Note that *lock* is a keyword-only argument.
1118
1119.. function:: copy(obj)
1120
1121 Return a ctypes object allocated from shared memory which is a copy of the
1122 ctypes object *obj*.
1123
1124.. function:: synchronized(obj[, lock])
1125
1126 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1127 synchronize access. If *lock* is ``None`` (the default) then a
1128 :class:`multiprocessing.RLock` object is created automatically.
1129
1130 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001131 object it wraps: :meth:`get_obj` returns the wrapped object and
1132 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001133
1134 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001135 than accessing the raw ctypes object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001136
1137
1138The table below compares the syntax for creating shared ctypes objects from
1139shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1140subclass of :class:`ctypes.Structure`.)
1141
1142==================== ========================== ===========================
1143ctypes sharedctypes using type sharedctypes using typecode
1144==================== ========================== ===========================
1145c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1146MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1147(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1148(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1149==================== ========================== ===========================
1150
1151
1152Below is an example where a number of ctypes objects are modified by a child
1153process::
1154
1155 from multiprocessing import Process, Lock
1156 from multiprocessing.sharedctypes import Value, Array
1157 from ctypes import Structure, c_double
1158
1159 class Point(Structure):
1160 _fields_ = [('x', c_double), ('y', c_double)]
1161
1162 def modify(n, x, s, A):
1163 n.value **= 2
1164 x.value **= 2
1165 s.value = s.value.upper()
1166 for a in A:
1167 a.x **= 2
1168 a.y **= 2
1169
1170 if __name__ == '__main__':
1171 lock = Lock()
1172
1173 n = Value('i', 7)
R. David Murray636b23a2009-04-28 16:08:18 +00001174 x = Value(c_double, 1.0/3.0, lock=False)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001175 s = Array('c', 'hello world', lock=lock)
1176 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1177
1178 p = Process(target=modify, args=(n, x, s, A))
1179 p.start()
1180 p.join()
1181
1182 print n.value
1183 print x.value
1184 print s.value
1185 print [(a.x, a.y) for a in A]
1186
1187
1188.. highlightlang:: none
1189
1190The results printed are ::
1191
1192 49
1193 0.1111111111111111
1194 HELLO WORLD
1195 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1196
1197.. highlightlang:: python
1198
1199
1200.. _multiprocessing-managers:
1201
1202Managers
1203~~~~~~~~
1204
1205Managers provide a way to create data which can be shared between different
1206processes. A manager object controls a server process which manages *shared
1207objects*. Other processes can access the shared objects by using proxies.
1208
1209.. function:: multiprocessing.Manager()
1210
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001211 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1212 can be used for sharing objects between processes. The returned manager
1213 object corresponds to a spawned child process and has methods which will
1214 create shared objects and return corresponding proxies.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001215
1216.. module:: multiprocessing.managers
1217 :synopsis: Share data between process with shared objects.
1218
1219Manager processes will be shutdown as soon as they are garbage collected or
1220their parent process exits. The manager classes are defined in the
1221:mod:`multiprocessing.managers` module:
1222
1223.. class:: BaseManager([address[, authkey]])
1224
1225 Create a BaseManager object.
1226
Jack Diederich1605b332010-02-23 17:23:30 +00001227 Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001228 that the manager object refers to a started manager process.
1229
1230 *address* is the address on which the manager process listens for new
1231 connections. If *address* is ``None`` then an arbitrary one is chosen.
1232
1233 *authkey* is the authentication key which will be used to check the validity
1234 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001235 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001236 must be a string.
1237
Jesse Noller7152f6d2009-04-02 05:17:26 +00001238 .. method:: start([initializer[, initargs]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001239
Jesse Noller7152f6d2009-04-02 05:17:26 +00001240 Start a subprocess to start the manager. If *initializer* is not ``None``
1241 then the subprocess will call ``initializer(*initargs)`` when it starts.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001242
Jesse Nollera280fd72008-11-28 18:22:54 +00001243 .. method:: get_server()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001244
Jesse Nollera280fd72008-11-28 18:22:54 +00001245 Returns a :class:`Server` object which represents the actual server under
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001246 the control of the Manager. The :class:`Server` object supports the
R. David Murray636b23a2009-04-28 16:08:18 +00001247 :meth:`serve_forever` method::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001248
Georg Brandlfc29f272009-01-02 20:25:14 +00001249 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001250 >>> manager = BaseManager(address=('', 50000), authkey='abc')
1251 >>> server = manager.get_server()
1252 >>> server.serve_forever()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001253
R. David Murray636b23a2009-04-28 16:08:18 +00001254 :class:`Server` additionally has an :attr:`address` attribute.
Jesse Nollera280fd72008-11-28 18:22:54 +00001255
1256 .. method:: connect()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001257
R. David Murray636b23a2009-04-28 16:08:18 +00001258 Connect a local manager object to a remote manager process::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001259
Jesse Nollera280fd72008-11-28 18:22:54 +00001260 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001261 >>> m = BaseManager(address=('127.0.0.1', 5000), authkey='abc')
Jesse Nollera280fd72008-11-28 18:22:54 +00001262 >>> m.connect()
1263
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001264 .. method:: shutdown()
1265
1266 Stop the process used by the manager. This is only available if
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001267 :meth:`start` has been used to start the server process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001268
1269 This can be called multiple times.
1270
1271 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1272
1273 A classmethod which can be used for registering a type or callable with
1274 the manager class.
1275
1276 *typeid* is a "type identifier" which is used to identify a particular
1277 type of shared object. This must be a string.
1278
1279 *callable* is a callable used for creating objects for this type
1280 identifier. If a manager instance will be created using the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001281 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001282 ``False`` then this can be left as ``None``.
1283
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001284 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1285 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1286 class is created automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001287
1288 *exposed* is used to specify a sequence of method names which proxies for
1289 this typeid should be allowed to access using
Ezio Melotti207b5f42014-02-15 16:58:52 +02001290 :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001291 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1292 where no exposed list is specified, all "public methods" of the shared
1293 object will be accessible. (Here a "public method" means any attribute
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001294 which has a :meth:`~object.__call__` method and whose name does not begin
1295 with ``'_'``.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001296
1297 *method_to_typeid* is a mapping used to specify the return type of those
1298 exposed methods which should return a proxy. It maps method names to
1299 typeid strings. (If *method_to_typeid* is ``None`` then
1300 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1301 method's name is not a key of this mapping or if the mapping is ``None``
1302 then the object returned by the method will be copied by value.
1303
1304 *create_method* determines whether a method should be created with name
1305 *typeid* which can be used to tell the server process to create a new
1306 shared object and return a proxy for it. By default it is ``True``.
1307
1308 :class:`BaseManager` instances also have one read-only property:
1309
1310 .. attribute:: address
1311
1312 The address used by the manager.
1313
1314
1315.. class:: SyncManager
1316
1317 A subclass of :class:`BaseManager` which can be used for the synchronization
1318 of processes. Objects of this type are returned by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001319 :func:`multiprocessing.Manager`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001320
1321 It also supports creation of shared lists and dictionaries.
1322
1323 .. method:: BoundedSemaphore([value])
1324
1325 Create a shared :class:`threading.BoundedSemaphore` object and return a
1326 proxy for it.
1327
1328 .. method:: Condition([lock])
1329
1330 Create a shared :class:`threading.Condition` object and return a proxy for
1331 it.
1332
1333 If *lock* is supplied then it should be a proxy for a
1334 :class:`threading.Lock` or :class:`threading.RLock` object.
1335
1336 .. method:: Event()
1337
1338 Create a shared :class:`threading.Event` object and return a proxy for it.
1339
1340 .. method:: Lock()
1341
1342 Create a shared :class:`threading.Lock` object and return a proxy for it.
1343
1344 .. method:: Namespace()
1345
1346 Create a shared :class:`Namespace` object and return a proxy for it.
1347
1348 .. method:: Queue([maxsize])
1349
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001350 Create a shared :class:`Queue.Queue` object and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001351
1352 .. method:: RLock()
1353
1354 Create a shared :class:`threading.RLock` object and return a proxy for it.
1355
1356 .. method:: Semaphore([value])
1357
1358 Create a shared :class:`threading.Semaphore` object and return a proxy for
1359 it.
1360
1361 .. method:: Array(typecode, sequence)
1362
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001363 Create an array and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001364
1365 .. method:: Value(typecode, value)
1366
1367 Create an object with a writable ``value`` attribute and return a proxy
1368 for it.
1369
1370 .. method:: dict()
1371 dict(mapping)
1372 dict(sequence)
1373
1374 Create a shared ``dict`` object and return a proxy for it.
1375
1376 .. method:: list()
1377 list(sequence)
1378
1379 Create a shared ``list`` object and return a proxy for it.
1380
Georg Brandl78f11ed2010-11-26 07:34:20 +00001381 .. note::
1382
1383 Modifications to mutable values or items in dict and list proxies will not
1384 be propagated through the manager, because the proxy has no way of knowing
1385 when its values or items are modified. To modify such an item, you can
1386 re-assign the modified object to the container proxy::
1387
1388 # create a list proxy and append a mutable object (a dictionary)
1389 lproxy = manager.list()
1390 lproxy.append({})
1391 # now mutate the dictionary
1392 d = lproxy[0]
1393 d['a'] = 1
1394 d['b'] = 2
1395 # at this point, the changes to d are not yet synced, but by
1396 # reassigning the dictionary, the proxy is notified of the change
1397 lproxy[0] = d
1398
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001399
1400Namespace objects
1401>>>>>>>>>>>>>>>>>
1402
1403A namespace object has no public methods, but does have writable attributes.
1404Its representation shows the values of its attributes.
1405
1406However, when using a proxy for a namespace object, an attribute beginning with
R. David Murray636b23a2009-04-28 16:08:18 +00001407``'_'`` will be an attribute of the proxy and not an attribute of the referent:
1408
1409.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001410
1411 >>> manager = multiprocessing.Manager()
1412 >>> Global = manager.Namespace()
1413 >>> Global.x = 10
1414 >>> Global.y = 'hello'
1415 >>> Global._z = 12.3 # this is an attribute of the proxy
1416 >>> print Global
1417 Namespace(x=10, y='hello')
1418
1419
1420Customized managers
1421>>>>>>>>>>>>>>>>>>>
1422
1423To create one's own manager, one creates a subclass of :class:`BaseManager` and
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001424uses the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001425callables with the manager class. For example::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001426
1427 from multiprocessing.managers import BaseManager
1428
1429 class MathsClass(object):
1430 def add(self, x, y):
1431 return x + y
1432 def mul(self, x, y):
1433 return x * y
1434
1435 class MyManager(BaseManager):
1436 pass
1437
1438 MyManager.register('Maths', MathsClass)
1439
1440 if __name__ == '__main__':
1441 manager = MyManager()
1442 manager.start()
1443 maths = manager.Maths()
1444 print maths.add(4, 3) # prints 7
1445 print maths.mul(7, 8) # prints 56
1446
1447
1448Using a remote manager
1449>>>>>>>>>>>>>>>>>>>>>>
1450
1451It is possible to run a manager server on one machine and have clients use it
1452from other machines (assuming that the firewalls involved allow it).
1453
1454Running the following commands creates a server for a single shared queue which
1455remote clients can access::
1456
1457 >>> from multiprocessing.managers import BaseManager
1458 >>> import Queue
1459 >>> queue = Queue.Queue()
1460 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001461 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001462 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Nollera280fd72008-11-28 18:22:54 +00001463 >>> s = m.get_server()
R. David Murray636b23a2009-04-28 16:08:18 +00001464 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001465
1466One client can access the server as follows::
1467
1468 >>> from multiprocessing.managers import BaseManager
1469 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001470 >>> QueueManager.register('get_queue')
1471 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1472 >>> m.connect()
1473 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001474 >>> queue.put('hello')
1475
1476Another client can also use it::
1477
1478 >>> from multiprocessing.managers import BaseManager
1479 >>> class QueueManager(BaseManager): pass
R. David Murray636b23a2009-04-28 16:08:18 +00001480 >>> QueueManager.register('get_queue')
1481 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1482 >>> m.connect()
1483 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001484 >>> queue.get()
1485 'hello'
1486
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001487Local processes can also access that queue, using the code from above on the
Jesse Nollera280fd72008-11-28 18:22:54 +00001488client to access it remotely::
1489
1490 >>> from multiprocessing import Process, Queue
1491 >>> from multiprocessing.managers import BaseManager
1492 >>> class Worker(Process):
1493 ... def __init__(self, q):
1494 ... self.q = q
1495 ... super(Worker, self).__init__()
1496 ... def run(self):
1497 ... self.q.put('local hello')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001498 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001499 >>> queue = Queue()
1500 >>> w = Worker(queue)
1501 >>> w.start()
1502 >>> class QueueManager(BaseManager): pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001503 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001504 >>> QueueManager.register('get_queue', callable=lambda: queue)
1505 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1506 >>> s = m.get_server()
1507 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001508
1509Proxy Objects
1510~~~~~~~~~~~~~
1511
1512A proxy is an object which *refers* to a shared object which lives (presumably)
1513in a different process. The shared object is said to be the *referent* of the
1514proxy. Multiple proxy objects may have the same referent.
1515
1516A proxy object has methods which invoke corresponding methods of its referent
1517(although not every method of the referent will necessarily be available through
1518the proxy). A proxy can usually be used in most of the same ways that its
R. David Murray636b23a2009-04-28 16:08:18 +00001519referent can:
1520
1521.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001522
1523 >>> from multiprocessing import Manager
1524 >>> manager = Manager()
1525 >>> l = manager.list([i*i for i in range(10)])
1526 >>> print l
1527 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1528 >>> print repr(l)
R. David Murray636b23a2009-04-28 16:08:18 +00001529 <ListProxy object, typeid 'list' at 0x...>
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001530 >>> l[4]
1531 16
1532 >>> l[2:5]
1533 [4, 9, 16]
1534
1535Notice that applying :func:`str` to a proxy will return the representation of
1536the referent, whereas applying :func:`repr` will return the representation of
1537the proxy.
1538
1539An important feature of proxy objects is that they are picklable so they can be
1540passed between processes. Note, however, that if a proxy is sent to the
1541corresponding manager's process then unpickling it will produce the referent
R. David Murray636b23a2009-04-28 16:08:18 +00001542itself. This means, for example, that one shared object can contain a second:
1543
1544.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001545
1546 >>> a = manager.list()
1547 >>> b = manager.list()
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001548 >>> a.append(b) # referent of a now contains referent of b
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001549 >>> print a, b
1550 [[]] []
1551 >>> b.append('hello')
1552 >>> print a, b
1553 [['hello']] ['hello']
1554
1555.. note::
1556
1557 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
R. David Murray636b23a2009-04-28 16:08:18 +00001558 by value. So, for instance, we have:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001559
R. David Murray636b23a2009-04-28 16:08:18 +00001560 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001561
R. David Murray636b23a2009-04-28 16:08:18 +00001562 >>> manager.list([1,2,3]) == [1,2,3]
1563 False
1564
1565 One should just use a copy of the referent instead when making comparisons.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001566
1567.. class:: BaseProxy
1568
1569 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1570
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001571 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001572
1573 Call and return the result of a method of the proxy's referent.
1574
1575 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1576
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001577 proxy._callmethod(methodname, args, kwds)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001578
1579 will evaluate the expression ::
1580
1581 getattr(obj, methodname)(*args, **kwds)
1582
1583 in the manager's process.
1584
1585 The returned value will be a copy of the result of the call or a proxy to
1586 a new shared object -- see documentation for the *method_to_typeid*
1587 argument of :meth:`BaseManager.register`.
1588
Ezio Melotti1e87da12011-10-19 10:39:35 +03001589 If an exception is raised by the call, then is re-raised by
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001590 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001591 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001592 raised by :meth:`_callmethod`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001593
1594 Note in particular that an exception will be raised if *methodname* has
1595 not been *exposed*
1596
R. David Murray636b23a2009-04-28 16:08:18 +00001597 An example of the usage of :meth:`_callmethod`:
1598
1599 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001600
1601 >>> l = manager.list(range(10))
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001602 >>> l._callmethod('__len__')
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001603 10
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001604 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001605 [2, 3, 4, 5, 6]
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001606 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001607 Traceback (most recent call last):
1608 ...
1609 IndexError: list index out of range
1610
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001611 .. method:: _getvalue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001612
1613 Return a copy of the referent.
1614
1615 If the referent is unpicklable then this will raise an exception.
1616
1617 .. method:: __repr__
1618
1619 Return a representation of the proxy object.
1620
1621 .. method:: __str__
1622
1623 Return the representation of the referent.
1624
1625
1626Cleanup
1627>>>>>>>
1628
1629A proxy object uses a weakref callback so that when it gets garbage collected it
1630deregisters itself from the manager which owns its referent.
1631
1632A shared object gets deleted from the manager process when there are no longer
1633any proxies referring to it.
1634
1635
1636Process Pools
1637~~~~~~~~~~~~~
1638
1639.. module:: multiprocessing.pool
1640 :synopsis: Create pools of processes.
1641
1642One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001643with the :class:`Pool` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001644
Jesse Noller654ade32010-01-27 03:05:57 +00001645.. class:: multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001646
1647 A process pool object which controls a pool of worker processes to which jobs
1648 can be submitted. It supports asynchronous results with timeouts and
1649 callbacks and has a parallel map implementation.
1650
1651 *processes* is the number of worker processes to use. If *processes* is
1652 ``None`` then the number returned by :func:`cpu_count` is used. If
1653 *initializer* is not ``None`` then each worker process will call
1654 ``initializer(*initargs)`` when it starts.
1655
Richard Oudkerk49032532013-07-02 12:31:50 +01001656 Note that the methods of the pool object should only be called by
1657 the process which created the pool.
1658
Georg Brandl92e69722010-10-17 06:21:30 +00001659 .. versionadded:: 2.7
1660 *maxtasksperchild* is the number of tasks a worker process can complete
1661 before it will exit and be replaced with a fresh worker process, to enable
1662 unused resources to be freed. The default *maxtasksperchild* is None, which
1663 means worker processes will live as long as the pool.
Jesse Noller654ade32010-01-27 03:05:57 +00001664
1665 .. note::
1666
Georg Brandl92e69722010-10-17 06:21:30 +00001667 Worker processes within a :class:`Pool` typically live for the complete
1668 duration of the Pool's work queue. A frequent pattern found in other
1669 systems (such as Apache, mod_wsgi, etc) to free resources held by
1670 workers is to allow a worker within a pool to complete only a set
1671 amount of work before being exiting, being cleaned up and a new
1672 process spawned to replace the old one. The *maxtasksperchild*
1673 argument to the :class:`Pool` exposes this ability to the end user.
Jesse Noller654ade32010-01-27 03:05:57 +00001674
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001675 .. method:: apply(func[, args[, kwds]])
1676
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001677 Equivalent of the :func:`apply` built-in function. It blocks until the
1678 result is ready, so :meth:`apply_async` is better suited for performing
1679 work in parallel. Additionally, *func* is only executed in one of the
1680 workers of the pool.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001681
1682 .. method:: apply_async(func[, args[, kwds[, callback]]])
1683
1684 A variant of the :meth:`apply` method which returns a result object.
1685
1686 If *callback* is specified then it should be a callable which accepts a
1687 single argument. When the result becomes ready *callback* is applied to
1688 it (unless the call failed). *callback* should complete immediately since
1689 otherwise the thread which handles the results will get blocked.
1690
1691 .. method:: map(func, iterable[, chunksize])
1692
Georg Brandld7d4fd72009-07-26 14:37:28 +00001693 A parallel equivalent of the :func:`map` built-in function (it supports only
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001694 one *iterable* argument though). It blocks until the result is ready.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001695
1696 This method chops the iterable into a number of chunks which it submits to
1697 the process pool as separate tasks. The (approximate) size of these
1698 chunks can be specified by setting *chunksize* to a positive integer.
1699
Senthil Kumaran0fc13ae2011-11-03 02:02:38 +08001700 .. method:: map_async(func, iterable[, chunksize[, callback]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001701
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001702 A variant of the :meth:`.map` method which returns a result object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001703
1704 If *callback* is specified then it should be a callable which accepts a
1705 single argument. When the result becomes ready *callback* is applied to
1706 it (unless the call failed). *callback* should complete immediately since
1707 otherwise the thread which handles the results will get blocked.
1708
1709 .. method:: imap(func, iterable[, chunksize])
1710
1711 An equivalent of :func:`itertools.imap`.
1712
1713 The *chunksize* argument is the same as the one used by the :meth:`.map`
1714 method. For very long iterables using a large value for *chunksize* can
Ezio Melotti1e87da12011-10-19 10:39:35 +03001715 make the job complete **much** faster than using the default value of
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001716 ``1``.
1717
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001718 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001719 returned by the :meth:`imap` method has an optional *timeout* parameter:
1720 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1721 result cannot be returned within *timeout* seconds.
1722
1723 .. method:: imap_unordered(func, iterable[, chunksize])
1724
1725 The same as :meth:`imap` except that the ordering of the results from the
1726 returned iterator should be considered arbitrary. (Only when there is
1727 only one worker process is the order guaranteed to be "correct".)
1728
1729 .. method:: close()
1730
1731 Prevents any more tasks from being submitted to the pool. Once all the
1732 tasks have been completed the worker processes will exit.
1733
1734 .. method:: terminate()
1735
1736 Stops the worker processes immediately without completing outstanding
1737 work. When the pool object is garbage collected :meth:`terminate` will be
1738 called immediately.
1739
1740 .. method:: join()
1741
1742 Wait for the worker processes to exit. One must call :meth:`close` or
1743 :meth:`terminate` before using :meth:`join`.
1744
1745
1746.. class:: AsyncResult
1747
1748 The class of the result returned by :meth:`Pool.apply_async` and
1749 :meth:`Pool.map_async`.
1750
Jesse Nollera280fd72008-11-28 18:22:54 +00001751 .. method:: get([timeout])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001752
1753 Return the result when it arrives. If *timeout* is not ``None`` and the
1754 result does not arrive within *timeout* seconds then
1755 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1756 an exception then that exception will be reraised by :meth:`get`.
1757
1758 .. method:: wait([timeout])
1759
1760 Wait until the result is available or until *timeout* seconds pass.
1761
1762 .. method:: ready()
1763
1764 Return whether the call has completed.
1765
1766 .. method:: successful()
1767
1768 Return whether the call completed without raising an exception. Will
1769 raise :exc:`AssertionError` if the result is not ready.
1770
1771The following example demonstrates the use of a pool::
1772
1773 from multiprocessing import Pool
1774
1775 def f(x):
1776 return x*x
1777
1778 if __name__ == '__main__':
1779 pool = Pool(processes=4) # start 4 worker processes
1780
Jesse Nollera280fd72008-11-28 18:22:54 +00001781 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001782 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
1783
1784 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
1785
1786 it = pool.imap(f, range(10))
1787 print it.next() # prints "0"
1788 print it.next() # prints "1"
1789 print it.next(timeout=1) # prints "4" unless your computer is *very* slow
1790
1791 import time
Jesse Nollera280fd72008-11-28 18:22:54 +00001792 result = pool.apply_async(time.sleep, (10,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001793 print result.get(timeout=1) # raises TimeoutError
1794
1795
1796.. _multiprocessing-listeners-clients:
1797
1798Listeners and Clients
1799~~~~~~~~~~~~~~~~~~~~~
1800
1801.. module:: multiprocessing.connection
1802 :synopsis: API for dealing with sockets.
1803
1804Usually message passing between processes is done using queues or by using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001805:class:`~multiprocessing.Connection` objects returned by
1806:func:`~multiprocessing.Pipe`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001807
1808However, the :mod:`multiprocessing.connection` module allows some extra
1809flexibility. It basically gives a high level message oriented API for dealing
1810with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001811authentication* using the :mod:`hmac` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001812
1813
1814.. function:: deliver_challenge(connection, authkey)
1815
1816 Send a randomly generated message to the other end of the connection and wait
1817 for a reply.
1818
1819 If the reply matches the digest of the message using *authkey* as the key
1820 then a welcome message is sent to the other end of the connection. Otherwise
1821 :exc:`AuthenticationError` is raised.
1822
Ezio Melotti3218f652013-04-10 17:59:20 +03001823.. function:: answer_challenge(connection, authkey)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001824
1825 Receive a message, calculate the digest of the message using *authkey* as the
1826 key, and then send the digest back.
1827
1828 If a welcome message is not received, then :exc:`AuthenticationError` is
1829 raised.
1830
1831.. function:: Client(address[, family[, authenticate[, authkey]]])
1832
1833 Attempt to set up a connection to the listener which is using address
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001834 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001835
1836 The type of the connection is determined by *family* argument, but this can
1837 generally be omitted since it can usually be inferred from the format of
1838 *address*. (See :ref:`multiprocessing-address-formats`)
1839
Jesse Noller34116922009-06-29 18:24:26 +00001840 If *authenticate* is ``True`` or *authkey* is a string then digest
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001841 authentication is used. The key used for authentication will be either
Benjamin Peterson73641d72008-08-20 14:07:59 +00001842 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001843 If authentication fails then :exc:`AuthenticationError` is raised. See
1844 :ref:`multiprocessing-auth-keys`.
1845
1846.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1847
1848 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1849 connections.
1850
1851 *address* is the address to be used by the bound socket or named pipe of the
1852 listener object.
1853
Jesse Nollerb12e79d2009-04-01 16:42:19 +00001854 .. note::
1855
1856 If an address of '0.0.0.0' is used, the address will not be a connectable
1857 end point on Windows. If you require a connectable end-point,
1858 you should use '127.0.0.1'.
1859
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001860 *family* is the type of socket (or named pipe) to use. This can be one of
1861 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1862 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1863 the first is guaranteed to be available. If *family* is ``None`` then the
1864 family is inferred from the format of *address*. If *address* is also
1865 ``None`` then a default is chosen. This default is the family which is
1866 assumed to be the fastest available. See
1867 :ref:`multiprocessing-address-formats`. Note that if *family* is
1868 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1869 private temporary directory created using :func:`tempfile.mkstemp`.
1870
1871 If the listener object uses a socket then *backlog* (1 by default) is passed
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001872 to the :meth:`~socket.socket.listen` method of the socket once it has been
1873 bound.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001874
1875 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1876 ``None`` then digest authentication is used.
1877
1878 If *authkey* is a string then it will be used as the authentication key;
1879 otherwise it must be *None*.
1880
1881 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001882 ``current_process().authkey`` is used as the authentication key. If
Jesse Noller34116922009-06-29 18:24:26 +00001883 *authkey* is ``None`` and *authenticate* is ``False`` then no
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001884 authentication is done. If authentication fails then
1885 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1886
1887 .. method:: accept()
1888
1889 Accept a connection on the bound socket or named pipe of the listener
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001890 object and return a :class:`~multiprocessing.Connection` object. If
1891 authentication is attempted and fails, then
1892 :exc:`~multiprocessing.AuthenticationError` is raised.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001893
1894 .. method:: close()
1895
1896 Close the bound socket or named pipe of the listener object. This is
1897 called automatically when the listener is garbage collected. However it
1898 is advisable to call it explicitly.
1899
1900 Listener objects have the following read-only properties:
1901
1902 .. attribute:: address
1903
1904 The address which is being used by the Listener object.
1905
1906 .. attribute:: last_accepted
1907
1908 The address from which the last accepted connection came. If this is
1909 unavailable then it is ``None``.
1910
1911
1912The module defines two exceptions:
1913
1914.. exception:: AuthenticationError
1915
1916 Exception raised when there is an authentication error.
1917
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001918
1919**Examples**
1920
1921The following server code creates a listener which uses ``'secret password'`` as
1922an authentication key. It then waits for a connection and sends some data to
1923the client::
1924
1925 from multiprocessing.connection import Listener
1926 from array import array
1927
1928 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
1929 listener = Listener(address, authkey='secret password')
1930
1931 conn = listener.accept()
1932 print 'connection accepted from', listener.last_accepted
1933
1934 conn.send([2.25, None, 'junk', float])
1935
1936 conn.send_bytes('hello')
1937
1938 conn.send_bytes(array('i', [42, 1729]))
1939
1940 conn.close()
1941 listener.close()
1942
1943The following code connects to the server and receives some data from the
1944server::
1945
1946 from multiprocessing.connection import Client
1947 from array import array
1948
1949 address = ('localhost', 6000)
1950 conn = Client(address, authkey='secret password')
1951
1952 print conn.recv() # => [2.25, None, 'junk', float]
1953
1954 print conn.recv_bytes() # => 'hello'
1955
1956 arr = array('i', [0, 0, 0, 0, 0])
1957 print conn.recv_bytes_into(arr) # => 8
1958 print arr # => array('i', [42, 1729, 0, 0, 0])
1959
1960 conn.close()
1961
1962
1963.. _multiprocessing-address-formats:
1964
1965Address Formats
1966>>>>>>>>>>>>>>>
1967
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001968* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001969 *hostname* is a string and *port* is an integer.
1970
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001971* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001972 filesystem.
1973
1974* An ``'AF_PIPE'`` address is a string of the form
Georg Brandl6b28f392008-12-27 19:06:04 +00001975 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandlfc29f272009-01-02 20:25:14 +00001976 pipe on a remote computer called *ServerName* one should use an address of the
Georg Brandldd7e3132009-01-04 10:24:09 +00001977 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001978
1979Note that any string beginning with two backslashes is assumed by default to be
1980an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
1981
1982
1983.. _multiprocessing-auth-keys:
1984
1985Authentication keys
1986~~~~~~~~~~~~~~~~~~~
1987
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001988When one uses :meth:`Connection.recv <multiprocessing.Connection.recv>`, the
1989data received is automatically
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001990unpickled. Unfortunately unpickling data from an untrusted source is a security
1991risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
1992to provide digest authentication.
1993
1994An authentication key is a string which can be thought of as a password: once a
1995connection is established both ends will demand proof that the other knows the
1996authentication key. (Demonstrating that both ends are using the same key does
1997**not** involve sending the key over the connection.)
1998
1999If authentication is requested but do authentication key is specified then the
Benjamin Peterson73641d72008-08-20 14:07:59 +00002000return value of ``current_process().authkey`` is used (see
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002001:class:`~multiprocessing.Process`). This value will automatically inherited by
2002any :class:`~multiprocessing.Process` object that the current process creates.
2003This means that (by default) all processes of a multi-process program will share
2004a single authentication key which can be used when setting up connections
Andrew M. Kuchlinga178a692009-04-03 21:45:29 +00002005between themselves.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002006
2007Suitable authentication keys can also be generated by using :func:`os.urandom`.
2008
2009
2010Logging
2011~~~~~~~
2012
2013Some support for logging is available. Note, however, that the :mod:`logging`
2014package does not use process shared locks so it is possible (depending on the
2015handler type) for messages from different processes to get mixed up.
2016
2017.. currentmodule:: multiprocessing
2018.. function:: get_logger()
2019
2020 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
2021 will be created.
2022
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002023 When first created the logger has level :data:`logging.NOTSET` and no
2024 default handler. Messages sent to this logger will not by default propagate
2025 to the root logger.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002026
2027 Note that on Windows child processes will only inherit the level of the
2028 parent process's logger -- any other customization of the logger will not be
2029 inherited.
2030
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002031.. currentmodule:: multiprocessing
2032.. function:: log_to_stderr()
2033
2034 This function performs a call to :func:`get_logger` but in addition to
2035 returning the logger created by get_logger, it adds a handler which sends
2036 output to :data:`sys.stderr` using format
2037 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2038
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002039Below is an example session with logging turned on::
2040
Georg Brandl19cc9442008-10-16 21:36:39 +00002041 >>> import multiprocessing, logging
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002042 >>> logger = multiprocessing.log_to_stderr()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002043 >>> logger.setLevel(logging.INFO)
2044 >>> logger.warning('doomed')
2045 [WARNING/MainProcess] doomed
Georg Brandl19cc9442008-10-16 21:36:39 +00002046 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002047 [INFO/SyncManager-...] child process calling self.run()
2048 [INFO/SyncManager-...] created temp directory /.../pymp-...
2049 [INFO/SyncManager-...] manager serving at '/.../listener-...'
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002050 >>> del m
2051 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002052 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002053
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002054In addition to having these two logging functions, the multiprocessing also
2055exposes two additional logging level attributes. These are :const:`SUBWARNING`
2056and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
2057normal level hierarchy.
2058
2059+----------------+----------------+
2060| Level | Numeric value |
2061+================+================+
2062| ``SUBWARNING`` | 25 |
2063+----------------+----------------+
2064| ``SUBDEBUG`` | 5 |
2065+----------------+----------------+
2066
2067For a full table of logging levels, see the :mod:`logging` module.
2068
2069These additional logging levels are used primarily for certain debug messages
2070within the multiprocessing module. Below is the same example as above, except
2071with :const:`SUBDEBUG` enabled::
2072
2073 >>> import multiprocessing, logging
2074 >>> logger = multiprocessing.log_to_stderr()
2075 >>> logger.setLevel(multiprocessing.SUBDEBUG)
2076 >>> logger.warning('doomed')
2077 [WARNING/MainProcess] doomed
2078 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002079 [INFO/SyncManager-...] child process calling self.run()
2080 [INFO/SyncManager-...] created temp directory /.../pymp-...
2081 [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002082 >>> del m
2083 [SUBDEBUG/MainProcess] finalizer calling ...
2084 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002085 [DEBUG/SyncManager-...] manager received shutdown message
2086 [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
2087 [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
2088 [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
2089 [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
2090 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002091
2092The :mod:`multiprocessing.dummy` module
2093~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2094
2095.. module:: multiprocessing.dummy
2096 :synopsis: Dumb wrapper around threading.
2097
2098:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002099no more than a wrapper around the :mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002100
2101
2102.. _multiprocessing-programming:
2103
2104Programming guidelines
2105----------------------
2106
2107There are certain guidelines and idioms which should be adhered to when using
2108:mod:`multiprocessing`.
2109
2110
2111All platforms
2112~~~~~~~~~~~~~
2113
2114Avoid shared state
2115
2116 As far as possible one should try to avoid shifting large amounts of data
2117 between processes.
2118
2119 It is probably best to stick to using queues or pipes for communication
2120 between processes rather than using the lower level synchronization
2121 primitives from the :mod:`threading` module.
2122
2123Picklability
2124
2125 Ensure that the arguments to the methods of proxies are picklable.
2126
2127Thread safety of proxies
2128
2129 Do not use a proxy object from more than one thread unless you protect it
2130 with a lock.
2131
2132 (There is never a problem with different processes using the *same* proxy.)
2133
2134Joining zombie processes
2135
2136 On Unix when a process finishes but has not been joined it becomes a zombie.
2137 There should never be very many because each time a new process starts (or
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002138 :func:`~multiprocessing.active_children` is called) all completed processes
2139 which have not yet been joined will be joined. Also calling a finished
2140 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
2141 join the process. Even so it is probably good
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002142 practice to explicitly join all the processes that you start.
2143
2144Better to inherit than pickle/unpickle
2145
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002146 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002147 that child processes can use them. However, one should generally avoid
2148 sending shared objects to other processes using pipes or queues. Instead
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002149 you should arrange the program so that a process which needs access to a
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002150 shared resource created elsewhere can inherit it from an ancestor process.
2151
2152Avoid terminating processes
2153
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002154 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
2155 method to stop a process is liable to
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002156 cause any shared resources (such as locks, semaphores, pipes and queues)
2157 currently being used by the process to become broken or unavailable to other
2158 processes.
2159
2160 Therefore it is probably best to only consider using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002161 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
2162 which never use any shared resources.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002163
2164Joining processes that use queues
2165
2166 Bear in mind that a process that has put items in a queue will wait before
2167 terminating until all the buffered items are fed by the "feeder" thread to
2168 the underlying pipe. (The child process can call the
Sandro Tosi8b48c662012-02-25 19:35:16 +01002169 :meth:`~multiprocessing.Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002170
2171 This means that whenever you use a queue you need to make sure that all
2172 items which have been put on the queue will eventually be removed before the
2173 process is joined. Otherwise you cannot be sure that processes which have
2174 put items on the queue will terminate. Remember also that non-daemonic
Zachary Ware06b74a72014-10-03 10:55:12 -05002175 processes will be joined automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002176
2177 An example which will deadlock is the following::
2178
2179 from multiprocessing import Process, Queue
2180
2181 def f(q):
2182 q.put('X' * 1000000)
2183
2184 if __name__ == '__main__':
2185 queue = Queue()
2186 p = Process(target=f, args=(queue,))
2187 p.start()
2188 p.join() # this deadlocks
2189 obj = queue.get()
2190
Zachary Ware06b74a72014-10-03 10:55:12 -05002191 A fix here would be to swap the last two lines (or simply remove the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002192 ``p.join()`` line).
2193
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002194Explicitly pass resources to child processes
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002195
2196 On Unix a child process can make use of a shared resource created in a
2197 parent process using a global resource. However, it is better to pass the
2198 object as an argument to the constructor for the child process.
2199
2200 Apart from making the code (potentially) compatible with Windows this also
2201 ensures that as long as the child process is still alive the object will not
2202 be garbage collected in the parent process. This might be important if some
2203 resource is freed when the object is garbage collected in the parent
2204 process.
2205
2206 So for instance ::
2207
2208 from multiprocessing import Process, Lock
2209
2210 def f():
2211 ... do something using "lock" ...
2212
2213 if __name__ == '__main__':
2214 lock = Lock()
2215 for i in range(10):
2216 Process(target=f).start()
2217
2218 should be rewritten as ::
2219
2220 from multiprocessing import Process, Lock
2221
2222 def f(l):
2223 ... do something using "l" ...
2224
2225 if __name__ == '__main__':
2226 lock = Lock()
2227 for i in range(10):
2228 Process(target=f, args=(lock,)).start()
2229
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002230Beware of replacing :data:`sys.stdin` with a "file like object"
Jesse Noller1b90efb2009-06-30 17:11:52 +00002231
2232 :mod:`multiprocessing` originally unconditionally called::
2233
2234 os.close(sys.stdin.fileno())
2235
R. David Murray321afa82009-07-01 02:49:10 +00002236 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
Jesse Noller1b90efb2009-06-30 17:11:52 +00002237 in issues with processes-in-processes. This has been changed to::
2238
2239 sys.stdin.close()
2240 sys.stdin = open(os.devnull)
2241
2242 Which solves the fundamental issue of processes colliding with each other
2243 resulting in a bad file descriptor error, but introduces a potential danger
2244 to applications which replace :func:`sys.stdin` with a "file-like object"
R. David Murray321afa82009-07-01 02:49:10 +00002245 with output buffering. This danger is that if multiple processes call
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002246 :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
Jesse Noller1b90efb2009-06-30 17:11:52 +00002247 data being flushed to the object multiple times, resulting in corruption.
2248
2249 If you write a file-like object and implement your own caching, you can
2250 make it fork-safe by storing the pid whenever you append to the cache,
2251 and discarding the cache when the pid changes. For example::
2252
2253 @property
2254 def cache(self):
2255 pid = os.getpid()
2256 if pid != self._pid:
2257 self._pid = pid
2258 self._cache = []
2259 return self._cache
2260
2261 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002262
2263Windows
2264~~~~~~~
2265
2266Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2267
2268More picklability
2269
2270 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2271 means, in particular, that bound or unbound methods cannot be used directly
2272 as the ``target`` argument on Windows --- just define a function and use
2273 that instead.
2274
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002275 Also, if you subclass :class:`~multiprocessing.Process` then make sure that
2276 instances will be picklable when the :meth:`Process.start
2277 <multiprocessing.Process.start>` method is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002278
2279Global variables
2280
2281 Bear in mind that if code run in a child process tries to access a global
2282 variable, then the value it sees (if any) may not be the same as the value
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002283 in the parent process at the time that :meth:`Process.start
2284 <multiprocessing.Process.start>` was called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002285
2286 However, global variables which are just module level constants cause no
2287 problems.
2288
2289Safe importing of main module
2290
2291 Make sure that the main module can be safely imported by a new Python
2292 interpreter without causing unintended side effects (such a starting a new
2293 process).
2294
2295 For example, under Windows running the following module would fail with a
2296 :exc:`RuntimeError`::
2297
2298 from multiprocessing import Process
2299
2300 def foo():
2301 print 'hello'
2302
2303 p = Process(target=foo)
2304 p.start()
2305
2306 Instead one should protect the "entry point" of the program by using ``if
2307 __name__ == '__main__':`` as follows::
2308
2309 from multiprocessing import Process, freeze_support
2310
2311 def foo():
2312 print 'hello'
2313
2314 if __name__ == '__main__':
2315 freeze_support()
2316 p = Process(target=foo)
2317 p.start()
2318
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002319 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002320 normally instead of frozen.)
2321
2322 This allows the newly spawned Python interpreter to safely import the module
2323 and then run the module's ``foo()`` function.
2324
2325 Similar restrictions apply if a pool or manager is created in the main
2326 module.
2327
2328
2329.. _multiprocessing-examples:
2330
2331Examples
2332--------
2333
2334Demonstration of how to create and use customized managers and proxies:
2335
2336.. literalinclude:: ../includes/mp_newtype.py
2337
2338
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002339Using :class:`~multiprocessing.pool.Pool`:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002340
2341.. literalinclude:: ../includes/mp_pool.py
2342
2343
2344Synchronization types like locks, conditions and queues:
2345
2346.. literalinclude:: ../includes/mp_synchronize.py
2347
2348
Georg Brandl21946af2010-10-06 09:28:45 +00002349An example showing how to use queues to feed tasks to a collection of worker
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002350processes and collect the results:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002351
2352.. literalinclude:: ../includes/mp_workers.py
2353
2354
2355An example of how a pool of worker processes can each run a
2356:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2357socket.
2358
2359.. literalinclude:: ../includes/mp_webserver.py
2360
2361
2362Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2363
2364.. literalinclude:: ../includes/mp_benchmarks.py
2365