blob: 2c765f551c1b5ceb590314d95d0f412a20988e8c [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
Berker Peksag0612ae52015-09-21 07:15:52 +0300911 A bounded semaphore object: a close analog of
912 :class:`threading.BoundedSemaphore`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000913
Berker Peksag0612ae52015-09-21 07:15:52 +0300914 A solitary difference from its close analog exists: its ``acquire`` method's
915 first argument is named *block* and it supports an optional second argument
916 *timeout*, as is consistent with :meth:`Lock.acquire`.
917
918 .. note::
919 On Mac OS X, this is indistinguishable from :class:`Semaphore` because
920 ``sem_getvalue()`` is not implemented on that platform.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000921
922.. class:: Condition([lock])
923
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000924 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000925
926 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
927 object from :mod:`multiprocessing`.
928
929.. class:: Event()
930
931 A clone of :class:`threading.Event`.
Jesse Noller02cb0eb2009-04-01 03:45:50 +0000932 This method returns the state of the internal semaphore on exit, so it
933 will always return ``True`` except if a timeout is given and the operation
934 times out.
935
936 .. versionchanged:: 2.7
937 Previously, the method always returned ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000938
Berker Peksag0612ae52015-09-21 07:15:52 +0300939
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000940.. class:: Lock()
941
Berker Peksag0612ae52015-09-21 07:15:52 +0300942 A non-recursive lock object: a close analog of :class:`threading.Lock`.
943 Once a process or thread has acquired a lock, subsequent attempts to
944 acquire it from any process or thread will block until it is released;
945 any process or thread may release it. The concepts and behaviors of
946 :class:`threading.Lock` as it applies to threads are replicated here in
947 :class:`multiprocessing.Lock` as it applies to either processes or threads,
948 except as noted.
949
950 Note that :class:`Lock` is actually a factory function which returns an
951 instance of ``multiprocessing.synchronize.Lock`` initialized with a
952 default context.
953
954 :class:`Lock` supports the :term:`context manager` protocol and thus may be
955 used in :keyword:`with` statements.
956
957 .. method:: acquire(block=True, timeout=None)
958
959 Acquire a lock, blocking or non-blocking.
960
961 With the *block* argument set to ``True`` (the default), the method call
962 will block until the lock is in an unlocked state, then set it to locked
963 and return ``True``. Note that the name of this first argument differs
964 from that in :meth:`threading.Lock.acquire`.
965
966 With the *block* argument set to ``False``, the method call does not
967 block. If the lock is currently in a locked state, return ``False``;
968 otherwise set the lock to a locked state and return ``True``.
969
970 When invoked with a positive, floating-point value for *timeout*, block
971 for at most the number of seconds specified by *timeout* as long as
972 the lock can not be acquired. Invocations with a negative value for
973 *timeout* are equivalent to a *timeout* of zero. Invocations with a
974 *timeout* value of ``None`` (the default) set the timeout period to
975 infinite. The *timeout* argument has no practical implications if the
976 *block* argument is set to ``False`` and is thus ignored. Returns
977 ``True`` if the lock has been acquired or ``False`` if the timeout period
978 has elapsed. Note that the *timeout* argument does not exist in this
979 method's analog, :meth:`threading.Lock.acquire`.
980
981 .. method:: release()
982
983 Release a lock. This can be called from any process or thread, not only
984 the process or thread which originally acquired the lock.
985
986 Behavior is the same as in :meth:`threading.Lock.release` except that
987 when invoked on an unlocked lock, a :exc:`ValueError` is raised.
988
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000989
990.. class:: RLock()
991
Berker Peksag0612ae52015-09-21 07:15:52 +0300992 A recursive lock object: a close analog of :class:`threading.RLock`. A
993 recursive lock must be released by the process or thread that acquired it.
994 Once a process or thread has acquired a recursive lock, the same process
995 or thread may acquire it again without blocking; that process or thread
996 must release it once for each time it has been acquired.
997
998 Note that :class:`RLock` is actually a factory function which returns an
999 instance of ``multiprocessing.synchronize.RLock`` initialized with a
1000 default context.
1001
1002 :class:`RLock` supports the :term:`context manager` protocol and thus may be
1003 used in :keyword:`with` statements.
1004
1005
1006 .. method:: acquire(block=True, timeout=None)
1007
1008 Acquire a lock, blocking or non-blocking.
1009
1010 When invoked with the *block* argument set to ``True``, block until the
1011 lock is in an unlocked state (not owned by any process or thread) unless
1012 the lock is already owned by the current process or thread. The current
1013 process or thread then takes ownership of the lock (if it does not
1014 already have ownership) and the recursion level inside the lock increments
1015 by one, resulting in a return value of ``True``. Note that there are
1016 several differences in this first argument's behavior compared to the
1017 implementation of :meth:`threading.RLock.acquire`, starting with the name
1018 of the argument itself.
1019
1020 When invoked with the *block* argument set to ``False``, do not block.
1021 If the lock has already been acquired (and thus is owned) by another
1022 process or thread, the current process or thread does not take ownership
1023 and the recursion level within the lock is not changed, resulting in
1024 a return value of ``False``. If the lock is in an unlocked state, the
1025 current process or thread takes ownership and the recursion level is
1026 incremented, resulting in a return value of ``True``.
1027
1028 Use and behaviors of the *timeout* argument are the same as in
1029 :meth:`Lock.acquire`. Note that the *timeout* argument does
1030 not exist in this method's analog, :meth:`threading.RLock.acquire`.
1031
1032
1033 .. method:: release()
1034
1035 Release a lock, decrementing the recursion level. If after the
1036 decrement the recursion level is zero, reset the lock to unlocked (not
1037 owned by any process or thread) and if any other processes or threads
1038 are blocked waiting for the lock to become unlocked, allow exactly one
1039 of them to proceed. If after the decrement the recursion level is still
1040 nonzero, the lock remains locked and owned by the calling process or
1041 thread.
1042
1043 Only call this method when the calling process or thread owns the lock.
1044 An :exc:`AssertionError` is raised if this method is called by a process
1045 or thread other than the owner or if the lock is in an unlocked (unowned)
1046 state. Note that the type of exception raised in this situation
1047 differs from the implemented behavior in :meth:`threading.RLock.release`.
1048
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001049
1050.. class:: Semaphore([value])
1051
Berker Peksag0612ae52015-09-21 07:15:52 +03001052 A semaphore object: a close analog of :class:`threading.Semaphore`.
1053
1054 A solitary difference from its close analog exists: its ``acquire`` method's
1055 first argument is named *block* and it supports an optional second argument
1056 *timeout*, as is consistent with :meth:`Lock.acquire`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001057
1058.. note::
1059
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001060 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001061 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
1062 by the equivalents in :mod:`threading`. The signature is
1063 ``acquire(block=True, timeout=None)`` with keyword parameters being
1064 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
1065 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
1066 ignored.
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001067
Georg Brandl042d6a42010-05-21 21:47:05 +00001068 On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
1069 a timeout will emulate that function's behavior using a sleeping loop.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001070
1071.. note::
1072
Serhiy Storchaka9b2e37f2015-09-12 17:47:12 +03001073 If the SIGINT signal generated by :kbd:`Ctrl-C` arrives while the main thread is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001074 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
1075 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
1076 or :meth:`Condition.wait` then the call will be immediately interrupted and
1077 :exc:`KeyboardInterrupt` will be raised.
1078
1079 This differs from the behaviour of :mod:`threading` where SIGINT will be
1080 ignored while the equivalent blocking calls are in progress.
1081
Berker Peksag928b3ff2015-04-08 18:12:53 +03001082.. note::
1083
1084 Some of this package's functionality requires a functioning shared semaphore
1085 implementation on the host operating system. Without one, the
1086 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
1087 import it will result in an :exc:`ImportError`. See
1088 :issue:`3770` for additional information.
1089
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001090
1091Shared :mod:`ctypes` Objects
1092~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1093
1094It is possible to create shared objects using shared memory which can be
1095inherited by child processes.
1096
Jesse Noller6ab22152009-01-18 02:45:38 +00001097.. function:: Value(typecode_or_type, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001098
1099 Return a :mod:`ctypes` object allocated from shared memory. By default the
1100 return value is actually a synchronized wrapper for the object.
1101
1102 *typecode_or_type* determines the type of the returned object: it is either a
1103 ctypes type or a one character typecode of the kind used by the :mod:`array`
1104 module. *\*args* is passed on to the constructor for the type.
1105
Richard Oudkerka69712c2013-11-17 17:00:38 +00001106 If *lock* is ``True`` (the default) then a new recursive lock
1107 object is created to synchronize access to the value. If *lock* is
1108 a :class:`Lock` or :class:`RLock` object then that will be used to
1109 synchronize access to the value. If *lock* is ``False`` then
1110 access to the returned object will not be automatically protected
1111 by a lock, so it will not necessarily be "process-safe".
1112
1113 Operations like ``+=`` which involve a read and write are not
1114 atomic. So if, for instance, you want to atomically increment a
1115 shared value it is insufficient to just do ::
1116
1117 counter.value += 1
1118
1119 Assuming the associated lock is recursive (which it is by default)
1120 you can instead do ::
1121
1122 with counter.get_lock():
1123 counter.value += 1
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001124
1125 Note that *lock* is a keyword-only argument.
1126
1127.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
1128
1129 Return a ctypes array allocated from shared memory. By default the return
1130 value is actually a synchronized wrapper for the array.
1131
1132 *typecode_or_type* determines the type of the elements of the returned array:
1133 it is either a ctypes type or a one character typecode of the kind used by
1134 the :mod:`array` module. If *size_or_initializer* is an integer, then it
1135 determines the length of the array, and the array will be initially zeroed.
1136 Otherwise, *size_or_initializer* is a sequence which is used to initialize
1137 the array and whose length determines the length of the array.
1138
1139 If *lock* is ``True`` (the default) then a new lock object is created to
1140 synchronize access to the value. If *lock* is a :class:`Lock` or
1141 :class:`RLock` object then that will be used to synchronize access to the
1142 value. If *lock* is ``False`` then access to the returned object will not be
1143 automatically protected by a lock, so it will not necessarily be
1144 "process-safe".
1145
1146 Note that *lock* is a keyword only argument.
1147
Georg Brandlb053f992008-11-22 08:34:14 +00001148 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001149 attributes which allow one to use it to store and retrieve strings.
1150
1151
1152The :mod:`multiprocessing.sharedctypes` module
1153>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1154
1155.. module:: multiprocessing.sharedctypes
1156 :synopsis: Allocate ctypes objects from shared memory.
1157
1158The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
1159:mod:`ctypes` objects from shared memory which can be inherited by child
1160processes.
1161
1162.. note::
1163
Benjamin Peterson90f36732008-07-12 20:16:19 +00001164 Although it is possible to store a pointer in shared memory remember that
1165 this will refer to a location in the address space of a specific process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001166 However, the pointer is quite likely to be invalid in the context of a second
1167 process and trying to dereference the pointer from the second process may
1168 cause a crash.
1169
1170.. function:: RawArray(typecode_or_type, size_or_initializer)
1171
1172 Return a ctypes array allocated from shared memory.
1173
1174 *typecode_or_type* determines the type of the elements of the returned array:
1175 it is either a ctypes type or a one character typecode of the kind used by
1176 the :mod:`array` module. If *size_or_initializer* is an integer then it
1177 determines the length of the array, and the array will be initially zeroed.
1178 Otherwise *size_or_initializer* is a sequence which is used to initialize the
1179 array and whose length determines the length of the array.
1180
1181 Note that setting and getting an element is potentially non-atomic -- use
1182 :func:`Array` instead to make sure that access is automatically synchronized
1183 using a lock.
1184
1185.. function:: RawValue(typecode_or_type, *args)
1186
1187 Return a ctypes object allocated from shared memory.
1188
1189 *typecode_or_type* determines the type of the returned object: it is either a
1190 ctypes type or a one character typecode of the kind used by the :mod:`array`
Jesse Noller6ab22152009-01-18 02:45:38 +00001191 module. *\*args* is passed on to the constructor for the type.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001192
1193 Note that setting and getting the value is potentially non-atomic -- use
1194 :func:`Value` instead to make sure that access is automatically synchronized
1195 using a lock.
1196
Georg Brandlb053f992008-11-22 08:34:14 +00001197 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001198 attributes which allow one to use it to store and retrieve strings -- see
1199 documentation for :mod:`ctypes`.
1200
Jesse Noller6ab22152009-01-18 02:45:38 +00001201.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001202
1203 The same as :func:`RawArray` except that depending on the value of *lock* a
1204 process-safe synchronization wrapper may be returned instead of a raw ctypes
1205 array.
1206
1207 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001208 synchronize access to the value. If *lock* is a
1209 :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
1210 then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001211 value. If *lock* is ``False`` then access to the returned object will not be
1212 automatically protected by a lock, so it will not necessarily be
1213 "process-safe".
1214
1215 Note that *lock* is a keyword-only argument.
1216
1217.. function:: Value(typecode_or_type, *args[, lock])
1218
1219 The same as :func:`RawValue` except that depending on the value of *lock* a
1220 process-safe synchronization wrapper may be returned instead of a raw ctypes
1221 object.
1222
1223 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001224 synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or
1225 :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001226 value. If *lock* is ``False`` then access to the returned object will not be
1227 automatically protected by a lock, so it will not necessarily be
1228 "process-safe".
1229
1230 Note that *lock* is a keyword-only argument.
1231
1232.. function:: copy(obj)
1233
1234 Return a ctypes object allocated from shared memory which is a copy of the
1235 ctypes object *obj*.
1236
1237.. function:: synchronized(obj[, lock])
1238
1239 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1240 synchronize access. If *lock* is ``None`` (the default) then a
1241 :class:`multiprocessing.RLock` object is created automatically.
1242
1243 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001244 object it wraps: :meth:`get_obj` returns the wrapped object and
1245 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001246
1247 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001248 than accessing the raw ctypes object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001249
1250
1251The table below compares the syntax for creating shared ctypes objects from
1252shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1253subclass of :class:`ctypes.Structure`.)
1254
1255==================== ========================== ===========================
1256ctypes sharedctypes using type sharedctypes using typecode
1257==================== ========================== ===========================
1258c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1259MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1260(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1261(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1262==================== ========================== ===========================
1263
1264
1265Below is an example where a number of ctypes objects are modified by a child
1266process::
1267
1268 from multiprocessing import Process, Lock
1269 from multiprocessing.sharedctypes import Value, Array
1270 from ctypes import Structure, c_double
1271
1272 class Point(Structure):
1273 _fields_ = [('x', c_double), ('y', c_double)]
1274
1275 def modify(n, x, s, A):
1276 n.value **= 2
1277 x.value **= 2
1278 s.value = s.value.upper()
1279 for a in A:
1280 a.x **= 2
1281 a.y **= 2
1282
1283 if __name__ == '__main__':
1284 lock = Lock()
1285
1286 n = Value('i', 7)
R. David Murray636b23a2009-04-28 16:08:18 +00001287 x = Value(c_double, 1.0/3.0, lock=False)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001288 s = Array('c', 'hello world', lock=lock)
1289 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1290
1291 p = Process(target=modify, args=(n, x, s, A))
1292 p.start()
1293 p.join()
1294
1295 print n.value
1296 print x.value
1297 print s.value
1298 print [(a.x, a.y) for a in A]
1299
1300
1301.. highlightlang:: none
1302
1303The results printed are ::
1304
1305 49
1306 0.1111111111111111
1307 HELLO WORLD
1308 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1309
1310.. highlightlang:: python
1311
1312
1313.. _multiprocessing-managers:
1314
1315Managers
1316~~~~~~~~
1317
1318Managers provide a way to create data which can be shared between different
1319processes. A manager object controls a server process which manages *shared
1320objects*. Other processes can access the shared objects by using proxies.
1321
1322.. function:: multiprocessing.Manager()
1323
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001324 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1325 can be used for sharing objects between processes. The returned manager
1326 object corresponds to a spawned child process and has methods which will
1327 create shared objects and return corresponding proxies.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001328
1329.. module:: multiprocessing.managers
1330 :synopsis: Share data between process with shared objects.
1331
1332Manager processes will be shutdown as soon as they are garbage collected or
1333their parent process exits. The manager classes are defined in the
1334:mod:`multiprocessing.managers` module:
1335
1336.. class:: BaseManager([address[, authkey]])
1337
1338 Create a BaseManager object.
1339
Jack Diederich1605b332010-02-23 17:23:30 +00001340 Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001341 that the manager object refers to a started manager process.
1342
1343 *address* is the address on which the manager process listens for new
1344 connections. If *address* is ``None`` then an arbitrary one is chosen.
1345
1346 *authkey* is the authentication key which will be used to check the validity
1347 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001348 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001349 must be a string.
1350
Jesse Noller7152f6d2009-04-02 05:17:26 +00001351 .. method:: start([initializer[, initargs]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001352
Jesse Noller7152f6d2009-04-02 05:17:26 +00001353 Start a subprocess to start the manager. If *initializer* is not ``None``
1354 then the subprocess will call ``initializer(*initargs)`` when it starts.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001355
Jesse Nollera280fd72008-11-28 18:22:54 +00001356 .. method:: get_server()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001357
Jesse Nollera280fd72008-11-28 18:22:54 +00001358 Returns a :class:`Server` object which represents the actual server under
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001359 the control of the Manager. The :class:`Server` object supports the
R. David Murray636b23a2009-04-28 16:08:18 +00001360 :meth:`serve_forever` method::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001361
Georg Brandlfc29f272009-01-02 20:25:14 +00001362 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001363 >>> manager = BaseManager(address=('', 50000), authkey='abc')
1364 >>> server = manager.get_server()
1365 >>> server.serve_forever()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001366
R. David Murray636b23a2009-04-28 16:08:18 +00001367 :class:`Server` additionally has an :attr:`address` attribute.
Jesse Nollera280fd72008-11-28 18:22:54 +00001368
1369 .. method:: connect()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001370
R. David Murray636b23a2009-04-28 16:08:18 +00001371 Connect a local manager object to a remote manager process::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001372
Jesse Nollera280fd72008-11-28 18:22:54 +00001373 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001374 >>> m = BaseManager(address=('127.0.0.1', 5000), authkey='abc')
Jesse Nollera280fd72008-11-28 18:22:54 +00001375 >>> m.connect()
1376
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001377 .. method:: shutdown()
1378
1379 Stop the process used by the manager. This is only available if
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001380 :meth:`start` has been used to start the server process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001381
1382 This can be called multiple times.
1383
1384 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1385
1386 A classmethod which can be used for registering a type or callable with
1387 the manager class.
1388
1389 *typeid* is a "type identifier" which is used to identify a particular
1390 type of shared object. This must be a string.
1391
1392 *callable* is a callable used for creating objects for this type
1393 identifier. If a manager instance will be created using the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001394 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001395 ``False`` then this can be left as ``None``.
1396
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001397 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1398 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1399 class is created automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001400
1401 *exposed* is used to specify a sequence of method names which proxies for
1402 this typeid should be allowed to access using
Ezio Melotti207b5f42014-02-15 16:58:52 +02001403 :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001404 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1405 where no exposed list is specified, all "public methods" of the shared
1406 object will be accessible. (Here a "public method" means any attribute
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001407 which has a :meth:`~object.__call__` method and whose name does not begin
1408 with ``'_'``.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001409
1410 *method_to_typeid* is a mapping used to specify the return type of those
1411 exposed methods which should return a proxy. It maps method names to
1412 typeid strings. (If *method_to_typeid* is ``None`` then
1413 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1414 method's name is not a key of this mapping or if the mapping is ``None``
1415 then the object returned by the method will be copied by value.
1416
1417 *create_method* determines whether a method should be created with name
1418 *typeid* which can be used to tell the server process to create a new
1419 shared object and return a proxy for it. By default it is ``True``.
1420
1421 :class:`BaseManager` instances also have one read-only property:
1422
1423 .. attribute:: address
1424
1425 The address used by the manager.
1426
1427
1428.. class:: SyncManager
1429
1430 A subclass of :class:`BaseManager` which can be used for the synchronization
1431 of processes. Objects of this type are returned by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001432 :func:`multiprocessing.Manager`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001433
1434 It also supports creation of shared lists and dictionaries.
1435
1436 .. method:: BoundedSemaphore([value])
1437
1438 Create a shared :class:`threading.BoundedSemaphore` object and return a
1439 proxy for it.
1440
1441 .. method:: Condition([lock])
1442
1443 Create a shared :class:`threading.Condition` object and return a proxy for
1444 it.
1445
1446 If *lock* is supplied then it should be a proxy for a
1447 :class:`threading.Lock` or :class:`threading.RLock` object.
1448
1449 .. method:: Event()
1450
1451 Create a shared :class:`threading.Event` object and return a proxy for it.
1452
1453 .. method:: Lock()
1454
1455 Create a shared :class:`threading.Lock` object and return a proxy for it.
1456
1457 .. method:: Namespace()
1458
1459 Create a shared :class:`Namespace` object and return a proxy for it.
1460
1461 .. method:: Queue([maxsize])
1462
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001463 Create a shared :class:`Queue.Queue` object and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001464
1465 .. method:: RLock()
1466
1467 Create a shared :class:`threading.RLock` object and return a proxy for it.
1468
1469 .. method:: Semaphore([value])
1470
1471 Create a shared :class:`threading.Semaphore` object and return a proxy for
1472 it.
1473
1474 .. method:: Array(typecode, sequence)
1475
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001476 Create an array and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001477
1478 .. method:: Value(typecode, value)
1479
1480 Create an object with a writable ``value`` attribute and return a proxy
1481 for it.
1482
1483 .. method:: dict()
1484 dict(mapping)
1485 dict(sequence)
1486
1487 Create a shared ``dict`` object and return a proxy for it.
1488
1489 .. method:: list()
1490 list(sequence)
1491
1492 Create a shared ``list`` object and return a proxy for it.
1493
Georg Brandl78f11ed2010-11-26 07:34:20 +00001494 .. note::
1495
1496 Modifications to mutable values or items in dict and list proxies will not
1497 be propagated through the manager, because the proxy has no way of knowing
1498 when its values or items are modified. To modify such an item, you can
1499 re-assign the modified object to the container proxy::
1500
1501 # create a list proxy and append a mutable object (a dictionary)
1502 lproxy = manager.list()
1503 lproxy.append({})
1504 # now mutate the dictionary
1505 d = lproxy[0]
1506 d['a'] = 1
1507 d['b'] = 2
1508 # at this point, the changes to d are not yet synced, but by
1509 # reassigning the dictionary, the proxy is notified of the change
1510 lproxy[0] = d
1511
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001512
1513Namespace objects
1514>>>>>>>>>>>>>>>>>
1515
1516A namespace object has no public methods, but does have writable attributes.
1517Its representation shows the values of its attributes.
1518
1519However, when using a proxy for a namespace object, an attribute beginning with
R. David Murray636b23a2009-04-28 16:08:18 +00001520``'_'`` will be an attribute of the proxy and not an attribute of the referent:
1521
1522.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001523
1524 >>> manager = multiprocessing.Manager()
1525 >>> Global = manager.Namespace()
1526 >>> Global.x = 10
1527 >>> Global.y = 'hello'
1528 >>> Global._z = 12.3 # this is an attribute of the proxy
1529 >>> print Global
1530 Namespace(x=10, y='hello')
1531
1532
1533Customized managers
1534>>>>>>>>>>>>>>>>>>>
1535
1536To create one's own manager, one creates a subclass of :class:`BaseManager` and
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001537uses the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001538callables with the manager class. For example::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001539
1540 from multiprocessing.managers import BaseManager
1541
1542 class MathsClass(object):
1543 def add(self, x, y):
1544 return x + y
1545 def mul(self, x, y):
1546 return x * y
1547
1548 class MyManager(BaseManager):
1549 pass
1550
1551 MyManager.register('Maths', MathsClass)
1552
1553 if __name__ == '__main__':
1554 manager = MyManager()
1555 manager.start()
1556 maths = manager.Maths()
1557 print maths.add(4, 3) # prints 7
1558 print maths.mul(7, 8) # prints 56
1559
1560
1561Using a remote manager
1562>>>>>>>>>>>>>>>>>>>>>>
1563
1564It is possible to run a manager server on one machine and have clients use it
1565from other machines (assuming that the firewalls involved allow it).
1566
1567Running the following commands creates a server for a single shared queue which
1568remote clients can access::
1569
1570 >>> from multiprocessing.managers import BaseManager
1571 >>> import Queue
1572 >>> queue = Queue.Queue()
1573 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001574 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001575 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Nollera280fd72008-11-28 18:22:54 +00001576 >>> s = m.get_server()
R. David Murray636b23a2009-04-28 16:08:18 +00001577 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001578
1579One client can access the server as follows::
1580
1581 >>> from multiprocessing.managers import BaseManager
1582 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001583 >>> QueueManager.register('get_queue')
1584 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1585 >>> m.connect()
1586 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001587 >>> queue.put('hello')
1588
1589Another client can also use it::
1590
1591 >>> from multiprocessing.managers import BaseManager
1592 >>> class QueueManager(BaseManager): pass
R. David Murray636b23a2009-04-28 16:08:18 +00001593 >>> QueueManager.register('get_queue')
1594 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1595 >>> m.connect()
1596 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001597 >>> queue.get()
1598 'hello'
1599
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001600Local processes can also access that queue, using the code from above on the
Jesse Nollera280fd72008-11-28 18:22:54 +00001601client to access it remotely::
1602
1603 >>> from multiprocessing import Process, Queue
1604 >>> from multiprocessing.managers import BaseManager
1605 >>> class Worker(Process):
1606 ... def __init__(self, q):
1607 ... self.q = q
1608 ... super(Worker, self).__init__()
1609 ... def run(self):
1610 ... self.q.put('local hello')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001611 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001612 >>> queue = Queue()
1613 >>> w = Worker(queue)
1614 >>> w.start()
1615 >>> class QueueManager(BaseManager): pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001616 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001617 >>> QueueManager.register('get_queue', callable=lambda: queue)
1618 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1619 >>> s = m.get_server()
1620 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001621
1622Proxy Objects
1623~~~~~~~~~~~~~
1624
1625A proxy is an object which *refers* to a shared object which lives (presumably)
1626in a different process. The shared object is said to be the *referent* of the
1627proxy. Multiple proxy objects may have the same referent.
1628
1629A proxy object has methods which invoke corresponding methods of its referent
1630(although not every method of the referent will necessarily be available through
1631the proxy). A proxy can usually be used in most of the same ways that its
R. David Murray636b23a2009-04-28 16:08:18 +00001632referent can:
1633
1634.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001635
1636 >>> from multiprocessing import Manager
1637 >>> manager = Manager()
1638 >>> l = manager.list([i*i for i in range(10)])
1639 >>> print l
1640 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1641 >>> print repr(l)
R. David Murray636b23a2009-04-28 16:08:18 +00001642 <ListProxy object, typeid 'list' at 0x...>
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001643 >>> l[4]
1644 16
1645 >>> l[2:5]
1646 [4, 9, 16]
1647
1648Notice that applying :func:`str` to a proxy will return the representation of
1649the referent, whereas applying :func:`repr` will return the representation of
1650the proxy.
1651
1652An important feature of proxy objects is that they are picklable so they can be
1653passed between processes. Note, however, that if a proxy is sent to the
1654corresponding manager's process then unpickling it will produce the referent
R. David Murray636b23a2009-04-28 16:08:18 +00001655itself. This means, for example, that one shared object can contain a second:
1656
1657.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001658
1659 >>> a = manager.list()
1660 >>> b = manager.list()
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001661 >>> a.append(b) # referent of a now contains referent of b
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001662 >>> print a, b
1663 [[]] []
1664 >>> b.append('hello')
1665 >>> print a, b
1666 [['hello']] ['hello']
1667
1668.. note::
1669
1670 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
R. David Murray636b23a2009-04-28 16:08:18 +00001671 by value. So, for instance, we have:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001672
R. David Murray636b23a2009-04-28 16:08:18 +00001673 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001674
R. David Murray636b23a2009-04-28 16:08:18 +00001675 >>> manager.list([1,2,3]) == [1,2,3]
1676 False
1677
1678 One should just use a copy of the referent instead when making comparisons.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001679
1680.. class:: BaseProxy
1681
1682 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1683
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001684 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001685
1686 Call and return the result of a method of the proxy's referent.
1687
1688 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1689
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001690 proxy._callmethod(methodname, args, kwds)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001691
1692 will evaluate the expression ::
1693
1694 getattr(obj, methodname)(*args, **kwds)
1695
1696 in the manager's process.
1697
1698 The returned value will be a copy of the result of the call or a proxy to
1699 a new shared object -- see documentation for the *method_to_typeid*
1700 argument of :meth:`BaseManager.register`.
1701
Ezio Melotti1e87da12011-10-19 10:39:35 +03001702 If an exception is raised by the call, then is re-raised by
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001703 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001704 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001705 raised by :meth:`_callmethod`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001706
1707 Note in particular that an exception will be raised if *methodname* has
Martin Panter4ed35fc2015-10-10 10:52:35 +00001708 not been *exposed*.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001709
R. David Murray636b23a2009-04-28 16:08:18 +00001710 An example of the usage of :meth:`_callmethod`:
1711
1712 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001713
1714 >>> l = manager.list(range(10))
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001715 >>> l._callmethod('__len__')
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001716 10
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001717 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001718 [2, 3, 4, 5, 6]
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001719 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001720 Traceback (most recent call last):
1721 ...
1722 IndexError: list index out of range
1723
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001724 .. method:: _getvalue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001725
1726 Return a copy of the referent.
1727
1728 If the referent is unpicklable then this will raise an exception.
1729
1730 .. method:: __repr__
1731
1732 Return a representation of the proxy object.
1733
1734 .. method:: __str__
1735
1736 Return the representation of the referent.
1737
1738
1739Cleanup
1740>>>>>>>
1741
1742A proxy object uses a weakref callback so that when it gets garbage collected it
1743deregisters itself from the manager which owns its referent.
1744
1745A shared object gets deleted from the manager process when there are no longer
1746any proxies referring to it.
1747
1748
1749Process Pools
1750~~~~~~~~~~~~~
1751
1752.. module:: multiprocessing.pool
1753 :synopsis: Create pools of processes.
1754
1755One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001756with the :class:`Pool` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001757
Jesse Noller654ade32010-01-27 03:05:57 +00001758.. class:: multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001759
1760 A process pool object which controls a pool of worker processes to which jobs
1761 can be submitted. It supports asynchronous results with timeouts and
1762 callbacks and has a parallel map implementation.
1763
1764 *processes* is the number of worker processes to use. If *processes* is
1765 ``None`` then the number returned by :func:`cpu_count` is used. If
1766 *initializer* is not ``None`` then each worker process will call
1767 ``initializer(*initargs)`` when it starts.
1768
Richard Oudkerk49032532013-07-02 12:31:50 +01001769 Note that the methods of the pool object should only be called by
1770 the process which created the pool.
1771
Georg Brandl92e69722010-10-17 06:21:30 +00001772 .. versionadded:: 2.7
1773 *maxtasksperchild* is the number of tasks a worker process can complete
1774 before it will exit and be replaced with a fresh worker process, to enable
1775 unused resources to be freed. The default *maxtasksperchild* is None, which
1776 means worker processes will live as long as the pool.
Jesse Noller654ade32010-01-27 03:05:57 +00001777
1778 .. note::
1779
Georg Brandl92e69722010-10-17 06:21:30 +00001780 Worker processes within a :class:`Pool` typically live for the complete
1781 duration of the Pool's work queue. A frequent pattern found in other
1782 systems (such as Apache, mod_wsgi, etc) to free resources held by
1783 workers is to allow a worker within a pool to complete only a set
1784 amount of work before being exiting, being cleaned up and a new
1785 process spawned to replace the old one. The *maxtasksperchild*
1786 argument to the :class:`Pool` exposes this ability to the end user.
Jesse Noller654ade32010-01-27 03:05:57 +00001787
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001788 .. method:: apply(func[, args[, kwds]])
1789
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001790 Equivalent of the :func:`apply` built-in function. It blocks until the
1791 result is ready, so :meth:`apply_async` is better suited for performing
1792 work in parallel. Additionally, *func* is only executed in one of the
1793 workers of the pool.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001794
1795 .. method:: apply_async(func[, args[, kwds[, callback]]])
1796
1797 A variant of the :meth:`apply` method which returns a result object.
1798
1799 If *callback* is specified then it should be a callable which accepts a
1800 single argument. When the result becomes ready *callback* is applied to
1801 it (unless the call failed). *callback* should complete immediately since
1802 otherwise the thread which handles the results will get blocked.
1803
1804 .. method:: map(func, iterable[, chunksize])
1805
Georg Brandld7d4fd72009-07-26 14:37:28 +00001806 A parallel equivalent of the :func:`map` built-in function (it supports only
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001807 one *iterable* argument though). It blocks until the result is ready.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001808
1809 This method chops the iterable into a number of chunks which it submits to
1810 the process pool as separate tasks. The (approximate) size of these
1811 chunks can be specified by setting *chunksize* to a positive integer.
1812
Senthil Kumaran0fc13ae2011-11-03 02:02:38 +08001813 .. method:: map_async(func, iterable[, chunksize[, callback]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001814
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001815 A variant of the :meth:`.map` method which returns a result object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001816
1817 If *callback* is specified then it should be a callable which accepts a
1818 single argument. When the result becomes ready *callback* is applied to
1819 it (unless the call failed). *callback* should complete immediately since
1820 otherwise the thread which handles the results will get blocked.
1821
1822 .. method:: imap(func, iterable[, chunksize])
1823
1824 An equivalent of :func:`itertools.imap`.
1825
1826 The *chunksize* argument is the same as the one used by the :meth:`.map`
1827 method. For very long iterables using a large value for *chunksize* can
Ezio Melotti1e87da12011-10-19 10:39:35 +03001828 make the job complete **much** faster than using the default value of
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001829 ``1``.
1830
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001831 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001832 returned by the :meth:`imap` method has an optional *timeout* parameter:
1833 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1834 result cannot be returned within *timeout* seconds.
1835
1836 .. method:: imap_unordered(func, iterable[, chunksize])
1837
1838 The same as :meth:`imap` except that the ordering of the results from the
1839 returned iterator should be considered arbitrary. (Only when there is
1840 only one worker process is the order guaranteed to be "correct".)
1841
1842 .. method:: close()
1843
1844 Prevents any more tasks from being submitted to the pool. Once all the
1845 tasks have been completed the worker processes will exit.
1846
1847 .. method:: terminate()
1848
1849 Stops the worker processes immediately without completing outstanding
1850 work. When the pool object is garbage collected :meth:`terminate` will be
1851 called immediately.
1852
1853 .. method:: join()
1854
1855 Wait for the worker processes to exit. One must call :meth:`close` or
1856 :meth:`terminate` before using :meth:`join`.
1857
1858
1859.. class:: AsyncResult
1860
1861 The class of the result returned by :meth:`Pool.apply_async` and
1862 :meth:`Pool.map_async`.
1863
Jesse Nollera280fd72008-11-28 18:22:54 +00001864 .. method:: get([timeout])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001865
1866 Return the result when it arrives. If *timeout* is not ``None`` and the
1867 result does not arrive within *timeout* seconds then
1868 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1869 an exception then that exception will be reraised by :meth:`get`.
1870
1871 .. method:: wait([timeout])
1872
1873 Wait until the result is available or until *timeout* seconds pass.
1874
1875 .. method:: ready()
1876
1877 Return whether the call has completed.
1878
1879 .. method:: successful()
1880
1881 Return whether the call completed without raising an exception. Will
1882 raise :exc:`AssertionError` if the result is not ready.
1883
1884The following example demonstrates the use of a pool::
1885
1886 from multiprocessing import Pool
1887
1888 def f(x):
1889 return x*x
1890
1891 if __name__ == '__main__':
1892 pool = Pool(processes=4) # start 4 worker processes
1893
Jesse Nollera280fd72008-11-28 18:22:54 +00001894 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001895 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
1896
1897 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
1898
1899 it = pool.imap(f, range(10))
1900 print it.next() # prints "0"
1901 print it.next() # prints "1"
1902 print it.next(timeout=1) # prints "4" unless your computer is *very* slow
1903
1904 import time
Jesse Nollera280fd72008-11-28 18:22:54 +00001905 result = pool.apply_async(time.sleep, (10,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001906 print result.get(timeout=1) # raises TimeoutError
1907
1908
1909.. _multiprocessing-listeners-clients:
1910
1911Listeners and Clients
1912~~~~~~~~~~~~~~~~~~~~~
1913
1914.. module:: multiprocessing.connection
1915 :synopsis: API for dealing with sockets.
1916
1917Usually message passing between processes is done using queues or by using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001918:class:`~multiprocessing.Connection` objects returned by
1919:func:`~multiprocessing.Pipe`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001920
1921However, the :mod:`multiprocessing.connection` module allows some extra
1922flexibility. It basically gives a high level message oriented API for dealing
1923with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001924authentication* using the :mod:`hmac` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001925
1926
1927.. function:: deliver_challenge(connection, authkey)
1928
1929 Send a randomly generated message to the other end of the connection and wait
1930 for a reply.
1931
1932 If the reply matches the digest of the message using *authkey* as the key
1933 then a welcome message is sent to the other end of the connection. Otherwise
1934 :exc:`AuthenticationError` is raised.
1935
Ezio Melotti3218f652013-04-10 17:59:20 +03001936.. function:: answer_challenge(connection, authkey)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001937
1938 Receive a message, calculate the digest of the message using *authkey* as the
1939 key, and then send the digest back.
1940
1941 If a welcome message is not received, then :exc:`AuthenticationError` is
1942 raised.
1943
1944.. function:: Client(address[, family[, authenticate[, authkey]]])
1945
1946 Attempt to set up a connection to the listener which is using address
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001947 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001948
1949 The type of the connection is determined by *family* argument, but this can
1950 generally be omitted since it can usually be inferred from the format of
1951 *address*. (See :ref:`multiprocessing-address-formats`)
1952
Jesse Noller34116922009-06-29 18:24:26 +00001953 If *authenticate* is ``True`` or *authkey* is a string then digest
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001954 authentication is used. The key used for authentication will be either
Benjamin Peterson73641d72008-08-20 14:07:59 +00001955 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001956 If authentication fails then :exc:`AuthenticationError` is raised. See
1957 :ref:`multiprocessing-auth-keys`.
1958
1959.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1960
1961 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1962 connections.
1963
1964 *address* is the address to be used by the bound socket or named pipe of the
1965 listener object.
1966
Jesse Nollerb12e79d2009-04-01 16:42:19 +00001967 .. note::
1968
1969 If an address of '0.0.0.0' is used, the address will not be a connectable
1970 end point on Windows. If you require a connectable end-point,
1971 you should use '127.0.0.1'.
1972
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001973 *family* is the type of socket (or named pipe) to use. This can be one of
1974 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1975 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1976 the first is guaranteed to be available. If *family* is ``None`` then the
1977 family is inferred from the format of *address*. If *address* is also
1978 ``None`` then a default is chosen. This default is the family which is
1979 assumed to be the fastest available. See
1980 :ref:`multiprocessing-address-formats`. Note that if *family* is
1981 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1982 private temporary directory created using :func:`tempfile.mkstemp`.
1983
1984 If the listener object uses a socket then *backlog* (1 by default) is passed
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001985 to the :meth:`~socket.socket.listen` method of the socket once it has been
1986 bound.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001987
1988 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1989 ``None`` then digest authentication is used.
1990
1991 If *authkey* is a string then it will be used as the authentication key;
1992 otherwise it must be *None*.
1993
1994 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001995 ``current_process().authkey`` is used as the authentication key. If
Jesse Noller34116922009-06-29 18:24:26 +00001996 *authkey* is ``None`` and *authenticate* is ``False`` then no
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001997 authentication is done. If authentication fails then
1998 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1999
2000 .. method:: accept()
2001
2002 Accept a connection on the bound socket or named pipe of the listener
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002003 object and return a :class:`~multiprocessing.Connection` object. If
2004 authentication is attempted and fails, then
2005 :exc:`~multiprocessing.AuthenticationError` is raised.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002006
2007 .. method:: close()
2008
2009 Close the bound socket or named pipe of the listener object. This is
2010 called automatically when the listener is garbage collected. However it
2011 is advisable to call it explicitly.
2012
2013 Listener objects have the following read-only properties:
2014
2015 .. attribute:: address
2016
2017 The address which is being used by the Listener object.
2018
2019 .. attribute:: last_accepted
2020
2021 The address from which the last accepted connection came. If this is
2022 unavailable then it is ``None``.
2023
2024
2025The module defines two exceptions:
2026
2027.. exception:: AuthenticationError
2028
2029 Exception raised when there is an authentication error.
2030
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002031
2032**Examples**
2033
2034The following server code creates a listener which uses ``'secret password'`` as
2035an authentication key. It then waits for a connection and sends some data to
2036the client::
2037
2038 from multiprocessing.connection import Listener
2039 from array import array
2040
2041 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
2042 listener = Listener(address, authkey='secret password')
2043
2044 conn = listener.accept()
2045 print 'connection accepted from', listener.last_accepted
2046
2047 conn.send([2.25, None, 'junk', float])
2048
2049 conn.send_bytes('hello')
2050
2051 conn.send_bytes(array('i', [42, 1729]))
2052
2053 conn.close()
2054 listener.close()
2055
2056The following code connects to the server and receives some data from the
2057server::
2058
2059 from multiprocessing.connection import Client
2060 from array import array
2061
2062 address = ('localhost', 6000)
2063 conn = Client(address, authkey='secret password')
2064
2065 print conn.recv() # => [2.25, None, 'junk', float]
2066
2067 print conn.recv_bytes() # => 'hello'
2068
2069 arr = array('i', [0, 0, 0, 0, 0])
2070 print conn.recv_bytes_into(arr) # => 8
2071 print arr # => array('i', [42, 1729, 0, 0, 0])
2072
2073 conn.close()
2074
2075
2076.. _multiprocessing-address-formats:
2077
2078Address Formats
2079>>>>>>>>>>>>>>>
2080
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002081* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002082 *hostname* is a string and *port* is an integer.
2083
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002084* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002085 filesystem.
2086
2087* An ``'AF_PIPE'`` address is a string of the form
Georg Brandl6b28f392008-12-27 19:06:04 +00002088 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandlfc29f272009-01-02 20:25:14 +00002089 pipe on a remote computer called *ServerName* one should use an address of the
Georg Brandldd7e3132009-01-04 10:24:09 +00002090 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002091
2092Note that any string beginning with two backslashes is assumed by default to be
2093an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
2094
2095
2096.. _multiprocessing-auth-keys:
2097
2098Authentication keys
2099~~~~~~~~~~~~~~~~~~~
2100
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002101When one uses :meth:`Connection.recv <multiprocessing.Connection.recv>`, the
2102data received is automatically
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002103unpickled. Unfortunately unpickling data from an untrusted source is a security
2104risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
2105to provide digest authentication.
2106
2107An authentication key is a string which can be thought of as a password: once a
2108connection is established both ends will demand proof that the other knows the
2109authentication key. (Demonstrating that both ends are using the same key does
2110**not** involve sending the key over the connection.)
2111
2112If authentication is requested but do authentication key is specified then the
Benjamin Peterson73641d72008-08-20 14:07:59 +00002113return value of ``current_process().authkey`` is used (see
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002114:class:`~multiprocessing.Process`). This value will automatically inherited by
2115any :class:`~multiprocessing.Process` object that the current process creates.
2116This means that (by default) all processes of a multi-process program will share
2117a single authentication key which can be used when setting up connections
Andrew M. Kuchlinga178a692009-04-03 21:45:29 +00002118between themselves.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002119
2120Suitable authentication keys can also be generated by using :func:`os.urandom`.
2121
2122
2123Logging
2124~~~~~~~
2125
2126Some support for logging is available. Note, however, that the :mod:`logging`
2127package does not use process shared locks so it is possible (depending on the
2128handler type) for messages from different processes to get mixed up.
2129
2130.. currentmodule:: multiprocessing
2131.. function:: get_logger()
2132
2133 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
2134 will be created.
2135
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002136 When first created the logger has level :data:`logging.NOTSET` and no
2137 default handler. Messages sent to this logger will not by default propagate
2138 to the root logger.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002139
2140 Note that on Windows child processes will only inherit the level of the
2141 parent process's logger -- any other customization of the logger will not be
2142 inherited.
2143
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002144.. currentmodule:: multiprocessing
2145.. function:: log_to_stderr()
2146
2147 This function performs a call to :func:`get_logger` but in addition to
2148 returning the logger created by get_logger, it adds a handler which sends
2149 output to :data:`sys.stderr` using format
2150 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2151
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002152Below is an example session with logging turned on::
2153
Georg Brandl19cc9442008-10-16 21:36:39 +00002154 >>> import multiprocessing, logging
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002155 >>> logger = multiprocessing.log_to_stderr()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002156 >>> logger.setLevel(logging.INFO)
2157 >>> logger.warning('doomed')
2158 [WARNING/MainProcess] doomed
Georg Brandl19cc9442008-10-16 21:36:39 +00002159 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002160 [INFO/SyncManager-...] child process calling self.run()
2161 [INFO/SyncManager-...] created temp directory /.../pymp-...
2162 [INFO/SyncManager-...] manager serving at '/.../listener-...'
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002163 >>> del m
2164 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002165 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002166
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002167In addition to having these two logging functions, the multiprocessing also
2168exposes two additional logging level attributes. These are :const:`SUBWARNING`
2169and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
2170normal level hierarchy.
2171
2172+----------------+----------------+
2173| Level | Numeric value |
2174+================+================+
2175| ``SUBWARNING`` | 25 |
2176+----------------+----------------+
2177| ``SUBDEBUG`` | 5 |
2178+----------------+----------------+
2179
2180For a full table of logging levels, see the :mod:`logging` module.
2181
2182These additional logging levels are used primarily for certain debug messages
2183within the multiprocessing module. Below is the same example as above, except
2184with :const:`SUBDEBUG` enabled::
2185
2186 >>> import multiprocessing, logging
2187 >>> logger = multiprocessing.log_to_stderr()
2188 >>> logger.setLevel(multiprocessing.SUBDEBUG)
2189 >>> logger.warning('doomed')
2190 [WARNING/MainProcess] doomed
2191 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002192 [INFO/SyncManager-...] child process calling self.run()
2193 [INFO/SyncManager-...] created temp directory /.../pymp-...
2194 [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002195 >>> del m
2196 [SUBDEBUG/MainProcess] finalizer calling ...
2197 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002198 [DEBUG/SyncManager-...] manager received shutdown message
2199 [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
2200 [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
2201 [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
2202 [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
2203 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002204
2205The :mod:`multiprocessing.dummy` module
2206~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2207
2208.. module:: multiprocessing.dummy
2209 :synopsis: Dumb wrapper around threading.
2210
2211:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002212no more than a wrapper around the :mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002213
2214
2215.. _multiprocessing-programming:
2216
2217Programming guidelines
2218----------------------
2219
2220There are certain guidelines and idioms which should be adhered to when using
2221:mod:`multiprocessing`.
2222
2223
2224All platforms
2225~~~~~~~~~~~~~
2226
2227Avoid shared state
2228
2229 As far as possible one should try to avoid shifting large amounts of data
2230 between processes.
2231
2232 It is probably best to stick to using queues or pipes for communication
2233 between processes rather than using the lower level synchronization
2234 primitives from the :mod:`threading` module.
2235
2236Picklability
2237
2238 Ensure that the arguments to the methods of proxies are picklable.
2239
2240Thread safety of proxies
2241
2242 Do not use a proxy object from more than one thread unless you protect it
2243 with a lock.
2244
2245 (There is never a problem with different processes using the *same* proxy.)
2246
2247Joining zombie processes
2248
2249 On Unix when a process finishes but has not been joined it becomes a zombie.
2250 There should never be very many because each time a new process starts (or
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002251 :func:`~multiprocessing.active_children` is called) all completed processes
2252 which have not yet been joined will be joined. Also calling a finished
2253 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
2254 join the process. Even so it is probably good
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002255 practice to explicitly join all the processes that you start.
2256
2257Better to inherit than pickle/unpickle
2258
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002259 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002260 that child processes can use them. However, one should generally avoid
2261 sending shared objects to other processes using pipes or queues. Instead
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002262 you should arrange the program so that a process which needs access to a
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002263 shared resource created elsewhere can inherit it from an ancestor process.
2264
2265Avoid terminating processes
2266
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002267 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
2268 method to stop a process is liable to
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002269 cause any shared resources (such as locks, semaphores, pipes and queues)
2270 currently being used by the process to become broken or unavailable to other
2271 processes.
2272
2273 Therefore it is probably best to only consider using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002274 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
2275 which never use any shared resources.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002276
2277Joining processes that use queues
2278
2279 Bear in mind that a process that has put items in a queue will wait before
2280 terminating until all the buffered items are fed by the "feeder" thread to
2281 the underlying pipe. (The child process can call the
Sandro Tosi8b48c662012-02-25 19:35:16 +01002282 :meth:`~multiprocessing.Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002283
2284 This means that whenever you use a queue you need to make sure that all
2285 items which have been put on the queue will eventually be removed before the
2286 process is joined. Otherwise you cannot be sure that processes which have
2287 put items on the queue will terminate. Remember also that non-daemonic
Zachary Ware06b74a72014-10-03 10:55:12 -05002288 processes will be joined automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002289
2290 An example which will deadlock is the following::
2291
2292 from multiprocessing import Process, Queue
2293
2294 def f(q):
2295 q.put('X' * 1000000)
2296
2297 if __name__ == '__main__':
2298 queue = Queue()
2299 p = Process(target=f, args=(queue,))
2300 p.start()
2301 p.join() # this deadlocks
2302 obj = queue.get()
2303
Zachary Ware06b74a72014-10-03 10:55:12 -05002304 A fix here would be to swap the last two lines (or simply remove the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002305 ``p.join()`` line).
2306
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002307Explicitly pass resources to child processes
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002308
2309 On Unix a child process can make use of a shared resource created in a
2310 parent process using a global resource. However, it is better to pass the
2311 object as an argument to the constructor for the child process.
2312
2313 Apart from making the code (potentially) compatible with Windows this also
2314 ensures that as long as the child process is still alive the object will not
2315 be garbage collected in the parent process. This might be important if some
2316 resource is freed when the object is garbage collected in the parent
2317 process.
2318
2319 So for instance ::
2320
2321 from multiprocessing import Process, Lock
2322
2323 def f():
2324 ... do something using "lock" ...
2325
2326 if __name__ == '__main__':
2327 lock = Lock()
2328 for i in range(10):
2329 Process(target=f).start()
2330
2331 should be rewritten as ::
2332
2333 from multiprocessing import Process, Lock
2334
2335 def f(l):
2336 ... do something using "l" ...
2337
2338 if __name__ == '__main__':
2339 lock = Lock()
2340 for i in range(10):
2341 Process(target=f, args=(lock,)).start()
2342
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002343Beware of replacing :data:`sys.stdin` with a "file like object"
Jesse Noller1b90efb2009-06-30 17:11:52 +00002344
2345 :mod:`multiprocessing` originally unconditionally called::
2346
2347 os.close(sys.stdin.fileno())
2348
R. David Murray321afa82009-07-01 02:49:10 +00002349 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
Jesse Noller1b90efb2009-06-30 17:11:52 +00002350 in issues with processes-in-processes. This has been changed to::
2351
2352 sys.stdin.close()
2353 sys.stdin = open(os.devnull)
2354
2355 Which solves the fundamental issue of processes colliding with each other
2356 resulting in a bad file descriptor error, but introduces a potential danger
2357 to applications which replace :func:`sys.stdin` with a "file-like object"
R. David Murray321afa82009-07-01 02:49:10 +00002358 with output buffering. This danger is that if multiple processes call
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002359 :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
Jesse Noller1b90efb2009-06-30 17:11:52 +00002360 data being flushed to the object multiple times, resulting in corruption.
2361
2362 If you write a file-like object and implement your own caching, you can
2363 make it fork-safe by storing the pid whenever you append to the cache,
2364 and discarding the cache when the pid changes. For example::
2365
2366 @property
2367 def cache(self):
2368 pid = os.getpid()
2369 if pid != self._pid:
2370 self._pid = pid
2371 self._cache = []
2372 return self._cache
2373
2374 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002375
2376Windows
2377~~~~~~~
2378
2379Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2380
2381More picklability
2382
2383 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2384 means, in particular, that bound or unbound methods cannot be used directly
2385 as the ``target`` argument on Windows --- just define a function and use
2386 that instead.
2387
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002388 Also, if you subclass :class:`~multiprocessing.Process` then make sure that
2389 instances will be picklable when the :meth:`Process.start
2390 <multiprocessing.Process.start>` method is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002391
2392Global variables
2393
2394 Bear in mind that if code run in a child process tries to access a global
2395 variable, then the value it sees (if any) may not be the same as the value
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002396 in the parent process at the time that :meth:`Process.start
2397 <multiprocessing.Process.start>` was called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002398
2399 However, global variables which are just module level constants cause no
2400 problems.
2401
2402Safe importing of main module
2403
2404 Make sure that the main module can be safely imported by a new Python
2405 interpreter without causing unintended side effects (such a starting a new
2406 process).
2407
2408 For example, under Windows running the following module would fail with a
2409 :exc:`RuntimeError`::
2410
2411 from multiprocessing import Process
2412
2413 def foo():
2414 print 'hello'
2415
2416 p = Process(target=foo)
2417 p.start()
2418
2419 Instead one should protect the "entry point" of the program by using ``if
2420 __name__ == '__main__':`` as follows::
2421
2422 from multiprocessing import Process, freeze_support
2423
2424 def foo():
2425 print 'hello'
2426
2427 if __name__ == '__main__':
2428 freeze_support()
2429 p = Process(target=foo)
2430 p.start()
2431
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002432 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002433 normally instead of frozen.)
2434
2435 This allows the newly spawned Python interpreter to safely import the module
2436 and then run the module's ``foo()`` function.
2437
2438 Similar restrictions apply if a pool or manager is created in the main
2439 module.
2440
2441
2442.. _multiprocessing-examples:
2443
2444Examples
2445--------
2446
2447Demonstration of how to create and use customized managers and proxies:
2448
2449.. literalinclude:: ../includes/mp_newtype.py
2450
2451
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002452Using :class:`~multiprocessing.pool.Pool`:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002453
2454.. literalinclude:: ../includes/mp_pool.py
2455
2456
2457Synchronization types like locks, conditions and queues:
2458
2459.. literalinclude:: ../includes/mp_synchronize.py
2460
2461
Georg Brandl21946af2010-10-06 09:28:45 +00002462An example showing how to use queues to feed tasks to a collection of worker
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002463processes and collect the results:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002464
2465.. literalinclude:: ../includes/mp_workers.py
2466
2467
2468An example of how a pool of worker processes can each run a
2469:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2470socket.
2471
2472.. literalinclude:: ../includes/mp_webserver.py
2473
2474
2475Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2476
2477.. literalinclude:: ../includes/mp_benchmarks.py
2478