blob: cab480610567f7a9f5d88a0ff5c82b53ca21b082 [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
Berker Peksag6b51ddf2016-01-07 18:49:53 +0200754 Calling ``freeze_support()`` has no effect when invoked on any operating
755 system other than Windows. In addition, if the module is being run
756 normally by the Python interpreter on Windows (the program has not been
757 frozen), then ``freeze_support()`` has no effect.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000758
759.. function:: set_executable()
760
Ezio Melotti062d2b52009-12-19 22:41:49 +0000761 Sets the path of the Python interpreter to use when starting a child process.
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000762 (By default :data:`sys.executable` is used). Embedders will probably need to
763 do some thing like ::
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000764
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200765 set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000766
R. David Murray636b23a2009-04-28 16:08:18 +0000767 before they can create child processes. (Windows only)
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000768
769
770.. note::
771
772 :mod:`multiprocessing` contains no analogues of
773 :func:`threading.active_count`, :func:`threading.enumerate`,
774 :func:`threading.settrace`, :func:`threading.setprofile`,
775 :class:`threading.Timer`, or :class:`threading.local`.
776
777
778Connection Objects
779~~~~~~~~~~~~~~~~~~
780
781Connection objects allow the sending and receiving of picklable objects or
782strings. They can be thought of as message oriented connected sockets.
783
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200784Connection objects are usually created using :func:`Pipe` -- see also
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000785:ref:`multiprocessing-listeners-clients`.
786
787.. class:: Connection
788
789 .. method:: send(obj)
790
791 Send an object to the other end of the connection which should be read
792 using :meth:`recv`.
793
Jesse Noller5053fbb2009-04-02 04:22:09 +0000794 The object must be picklable. Very large pickles (approximately 32 MB+,
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200795 though it depends on the OS) may raise a :exc:`ValueError` exception.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000796
797 .. method:: recv()
798
799 Return an object sent from the other end of the connection using
Sandro Tosif788cf72012-01-07 17:56:43 +0100800 :meth:`send`. Blocks until there its something to receive. Raises
801 :exc:`EOFError` if there is nothing left to receive
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000802 and the other end was closed.
803
804 .. method:: fileno()
805
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200806 Return the file descriptor or handle used by the connection.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000807
808 .. method:: close()
809
810 Close the connection.
811
812 This is called automatically when the connection is garbage collected.
813
814 .. method:: poll([timeout])
815
816 Return whether there is any data available to be read.
817
818 If *timeout* is not specified then it will return immediately. If
819 *timeout* is a number then this specifies the maximum time in seconds to
820 block. If *timeout* is ``None`` then an infinite timeout is used.
821
822 .. method:: send_bytes(buffer[, offset[, size]])
823
824 Send byte data from an object supporting the buffer interface as a
825 complete message.
826
827 If *offset* is given then data is read from that position in *buffer*. If
Jesse Noller5053fbb2009-04-02 04:22:09 +0000828 *size* is given then that many bytes will be read from buffer. Very large
829 buffers (approximately 32 MB+, though it depends on the OS) may raise a
Eli Bendersky4b76f8a2011-12-31 07:05:12 +0200830 :exc:`ValueError` exception
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000831
832 .. method:: recv_bytes([maxlength])
833
834 Return a complete message of byte data sent from the other end of the
Sandro Tosif788cf72012-01-07 17:56:43 +0100835 connection as a string. Blocks until there is something to receive.
836 Raises :exc:`EOFError` if there is nothing left
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000837 to receive and the other end has closed.
838
839 If *maxlength* is specified and the message is longer than *maxlength*
840 then :exc:`IOError` is raised and the connection will no longer be
841 readable.
842
843 .. method:: recv_bytes_into(buffer[, offset])
844
845 Read into *buffer* a complete message of byte data sent from the other end
Sandro Tosif788cf72012-01-07 17:56:43 +0100846 of the connection and return the number of bytes in the message. Blocks
847 until there is something to receive. Raises
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000848 :exc:`EOFError` if there is nothing left to receive and the other end was
849 closed.
850
851 *buffer* must be an object satisfying the writable buffer interface. If
852 *offset* is given then the message will be written into the buffer from
R. David Murray636b23a2009-04-28 16:08:18 +0000853 that position. Offset must be a non-negative integer less than the
854 length of *buffer* (in bytes).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000855
856 If the buffer is too short then a :exc:`BufferTooShort` exception is
857 raised and the complete message is available as ``e.args[0]`` where ``e``
858 is the exception instance.
859
860
861For example:
862
R. David Murray636b23a2009-04-28 16:08:18 +0000863.. doctest::
864
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000865 >>> from multiprocessing import Pipe
866 >>> a, b = Pipe()
867 >>> a.send([1, 'hello', None])
868 >>> b.recv()
869 [1, 'hello', None]
870 >>> b.send_bytes('thank you')
871 >>> a.recv_bytes()
872 'thank you'
873 >>> import array
874 >>> arr1 = array.array('i', range(5))
875 >>> arr2 = array.array('i', [0] * 10)
876 >>> a.send_bytes(arr1)
877 >>> count = b.recv_bytes_into(arr2)
878 >>> assert count == len(arr1) * arr1.itemsize
879 >>> arr2
880 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
881
882
883.. warning::
884
885 The :meth:`Connection.recv` method automatically unpickles the data it
886 receives, which can be a security risk unless you can trust the process
887 which sent the message.
888
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000889 Therefore, unless the connection object was produced using :func:`Pipe` you
890 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
891 methods after performing some sort of authentication. See
892 :ref:`multiprocessing-auth-keys`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000893
894.. warning::
895
896 If a process is killed while it is trying to read or write to a pipe then
897 the data in the pipe is likely to become corrupted, because it may become
898 impossible to be sure where the message boundaries lie.
899
900
901Synchronization primitives
902~~~~~~~~~~~~~~~~~~~~~~~~~~
903
904Generally synchronization primitives are not as necessary in a multiprocess
Andrew M. Kuchling8ea605c2008-07-14 01:18:16 +0000905program as they are in a multithreaded program. See the documentation for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000906:mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000907
908Note that one can also create synchronization primitives by using a manager
909object -- see :ref:`multiprocessing-managers`.
910
911.. class:: BoundedSemaphore([value])
912
Berker Peksag0612ae52015-09-21 07:15:52 +0300913 A bounded semaphore object: a close analog of
914 :class:`threading.BoundedSemaphore`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000915
Berker Peksag0612ae52015-09-21 07:15:52 +0300916 A solitary difference from its close analog exists: its ``acquire`` method's
917 first argument is named *block* and it supports an optional second argument
918 *timeout*, as is consistent with :meth:`Lock.acquire`.
919
920 .. note::
921 On Mac OS X, this is indistinguishable from :class:`Semaphore` because
922 ``sem_getvalue()`` is not implemented on that platform.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000923
924.. class:: Condition([lock])
925
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000926 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000927
928 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
929 object from :mod:`multiprocessing`.
930
931.. class:: Event()
932
933 A clone of :class:`threading.Event`.
Jesse Noller02cb0eb2009-04-01 03:45:50 +0000934 This method returns the state of the internal semaphore on exit, so it
935 will always return ``True`` except if a timeout is given and the operation
936 times out.
937
938 .. versionchanged:: 2.7
939 Previously, the method always returned ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000940
Berker Peksag0612ae52015-09-21 07:15:52 +0300941
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000942.. class:: Lock()
943
Berker Peksag0612ae52015-09-21 07:15:52 +0300944 A non-recursive lock object: a close analog of :class:`threading.Lock`.
945 Once a process or thread has acquired a lock, subsequent attempts to
946 acquire it from any process or thread will block until it is released;
947 any process or thread may release it. The concepts and behaviors of
948 :class:`threading.Lock` as it applies to threads are replicated here in
949 :class:`multiprocessing.Lock` as it applies to either processes or threads,
950 except as noted.
951
952 Note that :class:`Lock` is actually a factory function which returns an
953 instance of ``multiprocessing.synchronize.Lock`` initialized with a
954 default context.
955
956 :class:`Lock` supports the :term:`context manager` protocol and thus may be
957 used in :keyword:`with` statements.
958
959 .. method:: acquire(block=True, timeout=None)
960
961 Acquire a lock, blocking or non-blocking.
962
963 With the *block* argument set to ``True`` (the default), the method call
964 will block until the lock is in an unlocked state, then set it to locked
965 and return ``True``. Note that the name of this first argument differs
966 from that in :meth:`threading.Lock.acquire`.
967
968 With the *block* argument set to ``False``, the method call does not
969 block. If the lock is currently in a locked state, return ``False``;
970 otherwise set the lock to a locked state and return ``True``.
971
972 When invoked with a positive, floating-point value for *timeout*, block
973 for at most the number of seconds specified by *timeout* as long as
974 the lock can not be acquired. Invocations with a negative value for
975 *timeout* are equivalent to a *timeout* of zero. Invocations with a
976 *timeout* value of ``None`` (the default) set the timeout period to
977 infinite. The *timeout* argument has no practical implications if the
978 *block* argument is set to ``False`` and is thus ignored. Returns
979 ``True`` if the lock has been acquired or ``False`` if the timeout period
980 has elapsed. Note that the *timeout* argument does not exist in this
981 method's analog, :meth:`threading.Lock.acquire`.
982
983 .. method:: release()
984
985 Release a lock. This can be called from any process or thread, not only
986 the process or thread which originally acquired the lock.
987
988 Behavior is the same as in :meth:`threading.Lock.release` except that
989 when invoked on an unlocked lock, a :exc:`ValueError` is raised.
990
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000991
992.. class:: RLock()
993
Berker Peksag0612ae52015-09-21 07:15:52 +0300994 A recursive lock object: a close analog of :class:`threading.RLock`. A
995 recursive lock must be released by the process or thread that acquired it.
996 Once a process or thread has acquired a recursive lock, the same process
997 or thread may acquire it again without blocking; that process or thread
998 must release it once for each time it has been acquired.
999
1000 Note that :class:`RLock` is actually a factory function which returns an
1001 instance of ``multiprocessing.synchronize.RLock`` initialized with a
1002 default context.
1003
1004 :class:`RLock` supports the :term:`context manager` protocol and thus may be
1005 used in :keyword:`with` statements.
1006
1007
1008 .. method:: acquire(block=True, timeout=None)
1009
1010 Acquire a lock, blocking or non-blocking.
1011
1012 When invoked with the *block* argument set to ``True``, block until the
1013 lock is in an unlocked state (not owned by any process or thread) unless
1014 the lock is already owned by the current process or thread. The current
1015 process or thread then takes ownership of the lock (if it does not
1016 already have ownership) and the recursion level inside the lock increments
1017 by one, resulting in a return value of ``True``. Note that there are
1018 several differences in this first argument's behavior compared to the
1019 implementation of :meth:`threading.RLock.acquire`, starting with the name
1020 of the argument itself.
1021
1022 When invoked with the *block* argument set to ``False``, do not block.
1023 If the lock has already been acquired (and thus is owned) by another
1024 process or thread, the current process or thread does not take ownership
1025 and the recursion level within the lock is not changed, resulting in
1026 a return value of ``False``. If the lock is in an unlocked state, the
1027 current process or thread takes ownership and the recursion level is
1028 incremented, resulting in a return value of ``True``.
1029
1030 Use and behaviors of the *timeout* argument are the same as in
1031 :meth:`Lock.acquire`. Note that the *timeout* argument does
1032 not exist in this method's analog, :meth:`threading.RLock.acquire`.
1033
1034
1035 .. method:: release()
1036
1037 Release a lock, decrementing the recursion level. If after the
1038 decrement the recursion level is zero, reset the lock to unlocked (not
1039 owned by any process or thread) and if any other processes or threads
1040 are blocked waiting for the lock to become unlocked, allow exactly one
1041 of them to proceed. If after the decrement the recursion level is still
1042 nonzero, the lock remains locked and owned by the calling process or
1043 thread.
1044
1045 Only call this method when the calling process or thread owns the lock.
1046 An :exc:`AssertionError` is raised if this method is called by a process
1047 or thread other than the owner or if the lock is in an unlocked (unowned)
1048 state. Note that the type of exception raised in this situation
1049 differs from the implemented behavior in :meth:`threading.RLock.release`.
1050
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001051
1052.. class:: Semaphore([value])
1053
Berker Peksag0612ae52015-09-21 07:15:52 +03001054 A semaphore object: a close analog of :class:`threading.Semaphore`.
1055
1056 A solitary difference from its close analog exists: its ``acquire`` method's
1057 first argument is named *block* and it supports an optional second argument
1058 *timeout*, as is consistent with :meth:`Lock.acquire`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001059
1060.. note::
1061
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001062 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001063 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
1064 by the equivalents in :mod:`threading`. The signature is
1065 ``acquire(block=True, timeout=None)`` with keyword parameters being
1066 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
1067 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
1068 ignored.
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001069
Georg Brandl042d6a42010-05-21 21:47:05 +00001070 On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
1071 a timeout will emulate that function's behavior using a sleeping loop.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001072
1073.. note::
1074
Serhiy Storchaka9b2e37f2015-09-12 17:47:12 +03001075 If the SIGINT signal generated by :kbd:`Ctrl-C` arrives while the main thread is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001076 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
1077 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
1078 or :meth:`Condition.wait` then the call will be immediately interrupted and
1079 :exc:`KeyboardInterrupt` will be raised.
1080
1081 This differs from the behaviour of :mod:`threading` where SIGINT will be
1082 ignored while the equivalent blocking calls are in progress.
1083
Berker Peksag928b3ff2015-04-08 18:12:53 +03001084.. note::
1085
1086 Some of this package's functionality requires a functioning shared semaphore
1087 implementation on the host operating system. Without one, the
1088 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
1089 import it will result in an :exc:`ImportError`. See
1090 :issue:`3770` for additional information.
1091
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001092
1093Shared :mod:`ctypes` Objects
1094~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1095
1096It is possible to create shared objects using shared memory which can be
1097inherited by child processes.
1098
Jesse Noller6ab22152009-01-18 02:45:38 +00001099.. function:: Value(typecode_or_type, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001100
1101 Return a :mod:`ctypes` object allocated from shared memory. By default the
1102 return value is actually a synchronized wrapper for the object.
1103
1104 *typecode_or_type* determines the type of the returned object: it is either a
1105 ctypes type or a one character typecode of the kind used by the :mod:`array`
1106 module. *\*args* is passed on to the constructor for the type.
1107
Richard Oudkerka69712c2013-11-17 17:00:38 +00001108 If *lock* is ``True`` (the default) then a new recursive lock
1109 object is created to synchronize access to the value. If *lock* is
1110 a :class:`Lock` or :class:`RLock` object then that will be used to
1111 synchronize access to the value. If *lock* is ``False`` then
1112 access to the returned object will not be automatically protected
1113 by a lock, so it will not necessarily be "process-safe".
1114
1115 Operations like ``+=`` which involve a read and write are not
1116 atomic. So if, for instance, you want to atomically increment a
1117 shared value it is insufficient to just do ::
1118
1119 counter.value += 1
1120
1121 Assuming the associated lock is recursive (which it is by default)
1122 you can instead do ::
1123
1124 with counter.get_lock():
1125 counter.value += 1
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001126
1127 Note that *lock* is a keyword-only argument.
1128
1129.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
1130
1131 Return a ctypes array allocated from shared memory. By default the return
1132 value is actually a synchronized wrapper for the array.
1133
1134 *typecode_or_type* determines the type of the elements of the returned array:
1135 it is either a ctypes type or a one character typecode of the kind used by
1136 the :mod:`array` module. If *size_or_initializer* is an integer, then it
1137 determines the length of the array, and the array will be initially zeroed.
1138 Otherwise, *size_or_initializer* is a sequence which is used to initialize
1139 the array and whose length determines the length of the array.
1140
1141 If *lock* is ``True`` (the default) then a new lock object is created to
1142 synchronize access to the value. If *lock* is a :class:`Lock` or
1143 :class:`RLock` object then that will be used to synchronize access to the
1144 value. If *lock* is ``False`` then access to the returned object will not be
1145 automatically protected by a lock, so it will not necessarily be
1146 "process-safe".
1147
1148 Note that *lock* is a keyword only argument.
1149
Georg Brandlb053f992008-11-22 08:34:14 +00001150 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001151 attributes which allow one to use it to store and retrieve strings.
1152
1153
1154The :mod:`multiprocessing.sharedctypes` module
1155>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1156
1157.. module:: multiprocessing.sharedctypes
1158 :synopsis: Allocate ctypes objects from shared memory.
1159
1160The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
1161:mod:`ctypes` objects from shared memory which can be inherited by child
1162processes.
1163
1164.. note::
1165
Benjamin Peterson90f36732008-07-12 20:16:19 +00001166 Although it is possible to store a pointer in shared memory remember that
1167 this will refer to a location in the address space of a specific process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001168 However, the pointer is quite likely to be invalid in the context of a second
1169 process and trying to dereference the pointer from the second process may
1170 cause a crash.
1171
1172.. function:: RawArray(typecode_or_type, size_or_initializer)
1173
1174 Return a ctypes array allocated from shared memory.
1175
1176 *typecode_or_type* determines the type of the elements of the returned array:
1177 it is either a ctypes type or a one character typecode of the kind used by
1178 the :mod:`array` module. If *size_or_initializer* is an integer then it
1179 determines the length of the array, and the array will be initially zeroed.
1180 Otherwise *size_or_initializer* is a sequence which is used to initialize the
1181 array and whose length determines the length of the array.
1182
1183 Note that setting and getting an element is potentially non-atomic -- use
1184 :func:`Array` instead to make sure that access is automatically synchronized
1185 using a lock.
1186
1187.. function:: RawValue(typecode_or_type, *args)
1188
1189 Return a ctypes object allocated from shared memory.
1190
1191 *typecode_or_type* determines the type of the returned object: it is either a
1192 ctypes type or a one character typecode of the kind used by the :mod:`array`
Jesse Noller6ab22152009-01-18 02:45:38 +00001193 module. *\*args* is passed on to the constructor for the type.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001194
1195 Note that setting and getting the value is potentially non-atomic -- use
1196 :func:`Value` instead to make sure that access is automatically synchronized
1197 using a lock.
1198
Georg Brandlb053f992008-11-22 08:34:14 +00001199 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001200 attributes which allow one to use it to store and retrieve strings -- see
1201 documentation for :mod:`ctypes`.
1202
Jesse Noller6ab22152009-01-18 02:45:38 +00001203.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001204
1205 The same as :func:`RawArray` except that depending on the value of *lock* a
1206 process-safe synchronization wrapper may be returned instead of a raw ctypes
1207 array.
1208
1209 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001210 synchronize access to the value. If *lock* is a
1211 :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
1212 then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001213 value. If *lock* is ``False`` then access to the returned object will not be
1214 automatically protected by a lock, so it will not necessarily be
1215 "process-safe".
1216
1217 Note that *lock* is a keyword-only argument.
1218
1219.. function:: Value(typecode_or_type, *args[, lock])
1220
1221 The same as :func:`RawValue` except that depending on the value of *lock* a
1222 process-safe synchronization wrapper may be returned instead of a raw ctypes
1223 object.
1224
1225 If *lock* is ``True`` (the default) then a new lock object is created to
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001226 synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or
1227 :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001228 value. If *lock* is ``False`` then access to the returned object will not be
1229 automatically protected by a lock, so it will not necessarily be
1230 "process-safe".
1231
1232 Note that *lock* is a keyword-only argument.
1233
1234.. function:: copy(obj)
1235
1236 Return a ctypes object allocated from shared memory which is a copy of the
1237 ctypes object *obj*.
1238
1239.. function:: synchronized(obj[, lock])
1240
1241 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1242 synchronize access. If *lock* is ``None`` (the default) then a
1243 :class:`multiprocessing.RLock` object is created automatically.
1244
1245 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001246 object it wraps: :meth:`get_obj` returns the wrapped object and
1247 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001248
1249 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001250 than accessing the raw ctypes object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001251
1252
1253The table below compares the syntax for creating shared ctypes objects from
1254shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1255subclass of :class:`ctypes.Structure`.)
1256
1257==================== ========================== ===========================
1258ctypes sharedctypes using type sharedctypes using typecode
1259==================== ========================== ===========================
1260c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1261MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1262(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1263(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1264==================== ========================== ===========================
1265
1266
1267Below is an example where a number of ctypes objects are modified by a child
1268process::
1269
1270 from multiprocessing import Process, Lock
1271 from multiprocessing.sharedctypes import Value, Array
1272 from ctypes import Structure, c_double
1273
1274 class Point(Structure):
1275 _fields_ = [('x', c_double), ('y', c_double)]
1276
1277 def modify(n, x, s, A):
1278 n.value **= 2
1279 x.value **= 2
1280 s.value = s.value.upper()
1281 for a in A:
1282 a.x **= 2
1283 a.y **= 2
1284
1285 if __name__ == '__main__':
1286 lock = Lock()
1287
1288 n = Value('i', 7)
R. David Murray636b23a2009-04-28 16:08:18 +00001289 x = Value(c_double, 1.0/3.0, lock=False)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001290 s = Array('c', 'hello world', lock=lock)
1291 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1292
1293 p = Process(target=modify, args=(n, x, s, A))
1294 p.start()
1295 p.join()
1296
1297 print n.value
1298 print x.value
1299 print s.value
1300 print [(a.x, a.y) for a in A]
1301
1302
1303.. highlightlang:: none
1304
1305The results printed are ::
1306
1307 49
1308 0.1111111111111111
1309 HELLO WORLD
1310 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1311
1312.. highlightlang:: python
1313
1314
1315.. _multiprocessing-managers:
1316
1317Managers
1318~~~~~~~~
1319
1320Managers provide a way to create data which can be shared between different
1321processes. A manager object controls a server process which manages *shared
1322objects*. Other processes can access the shared objects by using proxies.
1323
1324.. function:: multiprocessing.Manager()
1325
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001326 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1327 can be used for sharing objects between processes. The returned manager
1328 object corresponds to a spawned child process and has methods which will
1329 create shared objects and return corresponding proxies.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001330
1331.. module:: multiprocessing.managers
1332 :synopsis: Share data between process with shared objects.
1333
1334Manager processes will be shutdown as soon as they are garbage collected or
1335their parent process exits. The manager classes are defined in the
1336:mod:`multiprocessing.managers` module:
1337
1338.. class:: BaseManager([address[, authkey]])
1339
1340 Create a BaseManager object.
1341
Jack Diederich1605b332010-02-23 17:23:30 +00001342 Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001343 that the manager object refers to a started manager process.
1344
1345 *address* is the address on which the manager process listens for new
1346 connections. If *address* is ``None`` then an arbitrary one is chosen.
1347
1348 *authkey* is the authentication key which will be used to check the validity
1349 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001350 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001351 must be a string.
1352
Jesse Noller7152f6d2009-04-02 05:17:26 +00001353 .. method:: start([initializer[, initargs]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001354
Jesse Noller7152f6d2009-04-02 05:17:26 +00001355 Start a subprocess to start the manager. If *initializer* is not ``None``
1356 then the subprocess will call ``initializer(*initargs)`` when it starts.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001357
Jesse Nollera280fd72008-11-28 18:22:54 +00001358 .. method:: get_server()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001359
Jesse Nollera280fd72008-11-28 18:22:54 +00001360 Returns a :class:`Server` object which represents the actual server under
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001361 the control of the Manager. The :class:`Server` object supports the
R. David Murray636b23a2009-04-28 16:08:18 +00001362 :meth:`serve_forever` method::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001363
Georg Brandlfc29f272009-01-02 20:25:14 +00001364 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001365 >>> manager = BaseManager(address=('', 50000), authkey='abc')
1366 >>> server = manager.get_server()
1367 >>> server.serve_forever()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001368
R. David Murray636b23a2009-04-28 16:08:18 +00001369 :class:`Server` additionally has an :attr:`address` attribute.
Jesse Nollera280fd72008-11-28 18:22:54 +00001370
1371 .. method:: connect()
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001372
R. David Murray636b23a2009-04-28 16:08:18 +00001373 Connect a local manager object to a remote manager process::
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001374
Jesse Nollera280fd72008-11-28 18:22:54 +00001375 >>> from multiprocessing.managers import BaseManager
R. David Murray636b23a2009-04-28 16:08:18 +00001376 >>> m = BaseManager(address=('127.0.0.1', 5000), authkey='abc')
Jesse Nollera280fd72008-11-28 18:22:54 +00001377 >>> m.connect()
1378
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001379 .. method:: shutdown()
1380
1381 Stop the process used by the manager. This is only available if
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001382 :meth:`start` has been used to start the server process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001383
1384 This can be called multiple times.
1385
1386 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1387
1388 A classmethod which can be used for registering a type or callable with
1389 the manager class.
1390
1391 *typeid* is a "type identifier" which is used to identify a particular
1392 type of shared object. This must be a string.
1393
1394 *callable* is a callable used for creating objects for this type
1395 identifier. If a manager instance will be created using the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001396 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001397 ``False`` then this can be left as ``None``.
1398
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001399 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1400 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1401 class is created automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001402
1403 *exposed* is used to specify a sequence of method names which proxies for
1404 this typeid should be allowed to access using
Ezio Melotti207b5f42014-02-15 16:58:52 +02001405 :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001406 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1407 where no exposed list is specified, all "public methods" of the shared
1408 object will be accessible. (Here a "public method" means any attribute
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001409 which has a :meth:`~object.__call__` method and whose name does not begin
1410 with ``'_'``.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001411
1412 *method_to_typeid* is a mapping used to specify the return type of those
1413 exposed methods which should return a proxy. It maps method names to
1414 typeid strings. (If *method_to_typeid* is ``None`` then
1415 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1416 method's name is not a key of this mapping or if the mapping is ``None``
1417 then the object returned by the method will be copied by value.
1418
1419 *create_method* determines whether a method should be created with name
1420 *typeid* which can be used to tell the server process to create a new
1421 shared object and return a proxy for it. By default it is ``True``.
1422
1423 :class:`BaseManager` instances also have one read-only property:
1424
1425 .. attribute:: address
1426
1427 The address used by the manager.
1428
1429
1430.. class:: SyncManager
1431
1432 A subclass of :class:`BaseManager` which can be used for the synchronization
1433 of processes. Objects of this type are returned by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001434 :func:`multiprocessing.Manager`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001435
1436 It also supports creation of shared lists and dictionaries.
1437
1438 .. method:: BoundedSemaphore([value])
1439
1440 Create a shared :class:`threading.BoundedSemaphore` object and return a
1441 proxy for it.
1442
1443 .. method:: Condition([lock])
1444
1445 Create a shared :class:`threading.Condition` object and return a proxy for
1446 it.
1447
1448 If *lock* is supplied then it should be a proxy for a
1449 :class:`threading.Lock` or :class:`threading.RLock` object.
1450
1451 .. method:: Event()
1452
1453 Create a shared :class:`threading.Event` object and return a proxy for it.
1454
1455 .. method:: Lock()
1456
1457 Create a shared :class:`threading.Lock` object and return a proxy for it.
1458
1459 .. method:: Namespace()
1460
1461 Create a shared :class:`Namespace` object and return a proxy for it.
1462
1463 .. method:: Queue([maxsize])
1464
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001465 Create a shared :class:`Queue.Queue` object and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001466
1467 .. method:: RLock()
1468
1469 Create a shared :class:`threading.RLock` object and return a proxy for it.
1470
1471 .. method:: Semaphore([value])
1472
1473 Create a shared :class:`threading.Semaphore` object and return a proxy for
1474 it.
1475
1476 .. method:: Array(typecode, sequence)
1477
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001478 Create an array and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001479
1480 .. method:: Value(typecode, value)
1481
1482 Create an object with a writable ``value`` attribute and return a proxy
1483 for it.
1484
1485 .. method:: dict()
1486 dict(mapping)
1487 dict(sequence)
1488
1489 Create a shared ``dict`` object and return a proxy for it.
1490
1491 .. method:: list()
1492 list(sequence)
1493
1494 Create a shared ``list`` object and return a proxy for it.
1495
Georg Brandl78f11ed2010-11-26 07:34:20 +00001496 .. note::
1497
1498 Modifications to mutable values or items in dict and list proxies will not
1499 be propagated through the manager, because the proxy has no way of knowing
1500 when its values or items are modified. To modify such an item, you can
1501 re-assign the modified object to the container proxy::
1502
1503 # create a list proxy and append a mutable object (a dictionary)
1504 lproxy = manager.list()
1505 lproxy.append({})
1506 # now mutate the dictionary
1507 d = lproxy[0]
1508 d['a'] = 1
1509 d['b'] = 2
1510 # at this point, the changes to d are not yet synced, but by
1511 # reassigning the dictionary, the proxy is notified of the change
1512 lproxy[0] = d
1513
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001514
1515Namespace objects
1516>>>>>>>>>>>>>>>>>
1517
1518A namespace object has no public methods, but does have writable attributes.
1519Its representation shows the values of its attributes.
1520
1521However, when using a proxy for a namespace object, an attribute beginning with
R. David Murray636b23a2009-04-28 16:08:18 +00001522``'_'`` will be an attribute of the proxy and not an attribute of the referent:
1523
1524.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001525
1526 >>> manager = multiprocessing.Manager()
1527 >>> Global = manager.Namespace()
1528 >>> Global.x = 10
1529 >>> Global.y = 'hello'
1530 >>> Global._z = 12.3 # this is an attribute of the proxy
1531 >>> print Global
1532 Namespace(x=10, y='hello')
1533
1534
1535Customized managers
1536>>>>>>>>>>>>>>>>>>>
1537
1538To create one's own manager, one creates a subclass of :class:`BaseManager` and
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001539uses the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001540callables with the manager class. For example::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001541
1542 from multiprocessing.managers import BaseManager
1543
1544 class MathsClass(object):
1545 def add(self, x, y):
1546 return x + y
1547 def mul(self, x, y):
1548 return x * y
1549
1550 class MyManager(BaseManager):
1551 pass
1552
1553 MyManager.register('Maths', MathsClass)
1554
1555 if __name__ == '__main__':
1556 manager = MyManager()
1557 manager.start()
1558 maths = manager.Maths()
1559 print maths.add(4, 3) # prints 7
1560 print maths.mul(7, 8) # prints 56
1561
1562
1563Using a remote manager
1564>>>>>>>>>>>>>>>>>>>>>>
1565
1566It is possible to run a manager server on one machine and have clients use it
1567from other machines (assuming that the firewalls involved allow it).
1568
1569Running the following commands creates a server for a single shared queue which
1570remote clients can access::
1571
1572 >>> from multiprocessing.managers import BaseManager
1573 >>> import Queue
1574 >>> queue = Queue.Queue()
1575 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001576 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001577 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Nollera280fd72008-11-28 18:22:54 +00001578 >>> s = m.get_server()
R. David Murray636b23a2009-04-28 16:08:18 +00001579 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001580
1581One client can access the server as follows::
1582
1583 >>> from multiprocessing.managers import BaseManager
1584 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001585 >>> QueueManager.register('get_queue')
1586 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1587 >>> m.connect()
1588 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001589 >>> queue.put('hello')
1590
1591Another client can also use it::
1592
1593 >>> from multiprocessing.managers import BaseManager
1594 >>> class QueueManager(BaseManager): pass
R. David Murray636b23a2009-04-28 16:08:18 +00001595 >>> QueueManager.register('get_queue')
1596 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1597 >>> m.connect()
1598 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001599 >>> queue.get()
1600 'hello'
1601
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001602Local processes can also access that queue, using the code from above on the
Jesse Nollera280fd72008-11-28 18:22:54 +00001603client to access it remotely::
1604
1605 >>> from multiprocessing import Process, Queue
1606 >>> from multiprocessing.managers import BaseManager
1607 >>> class Worker(Process):
1608 ... def __init__(self, q):
1609 ... self.q = q
1610 ... super(Worker, self).__init__()
1611 ... def run(self):
1612 ... self.q.put('local hello')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001613 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001614 >>> queue = Queue()
1615 >>> w = Worker(queue)
1616 >>> w.start()
1617 >>> class QueueManager(BaseManager): pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001618 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001619 >>> QueueManager.register('get_queue', callable=lambda: queue)
1620 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1621 >>> s = m.get_server()
1622 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001623
1624Proxy Objects
1625~~~~~~~~~~~~~
1626
1627A proxy is an object which *refers* to a shared object which lives (presumably)
1628in a different process. The shared object is said to be the *referent* of the
1629proxy. Multiple proxy objects may have the same referent.
1630
1631A proxy object has methods which invoke corresponding methods of its referent
1632(although not every method of the referent will necessarily be available through
1633the proxy). A proxy can usually be used in most of the same ways that its
R. David Murray636b23a2009-04-28 16:08:18 +00001634referent can:
1635
1636.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001637
1638 >>> from multiprocessing import Manager
1639 >>> manager = Manager()
1640 >>> l = manager.list([i*i for i in range(10)])
1641 >>> print l
1642 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1643 >>> print repr(l)
R. David Murray636b23a2009-04-28 16:08:18 +00001644 <ListProxy object, typeid 'list' at 0x...>
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001645 >>> l[4]
1646 16
1647 >>> l[2:5]
1648 [4, 9, 16]
1649
1650Notice that applying :func:`str` to a proxy will return the representation of
1651the referent, whereas applying :func:`repr` will return the representation of
1652the proxy.
1653
1654An important feature of proxy objects is that they are picklable so they can be
1655passed between processes. Note, however, that if a proxy is sent to the
1656corresponding manager's process then unpickling it will produce the referent
R. David Murray636b23a2009-04-28 16:08:18 +00001657itself. This means, for example, that one shared object can contain a second:
1658
1659.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001660
1661 >>> a = manager.list()
1662 >>> b = manager.list()
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001663 >>> a.append(b) # referent of a now contains referent of b
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001664 >>> print a, b
1665 [[]] []
1666 >>> b.append('hello')
1667 >>> print a, b
1668 [['hello']] ['hello']
1669
1670.. note::
1671
1672 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
R. David Murray636b23a2009-04-28 16:08:18 +00001673 by value. So, for instance, we have:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001674
R. David Murray636b23a2009-04-28 16:08:18 +00001675 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001676
R. David Murray636b23a2009-04-28 16:08:18 +00001677 >>> manager.list([1,2,3]) == [1,2,3]
1678 False
1679
1680 One should just use a copy of the referent instead when making comparisons.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001681
1682.. class:: BaseProxy
1683
1684 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1685
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001686 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001687
1688 Call and return the result of a method of the proxy's referent.
1689
1690 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1691
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001692 proxy._callmethod(methodname, args, kwds)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001693
1694 will evaluate the expression ::
1695
1696 getattr(obj, methodname)(*args, **kwds)
1697
1698 in the manager's process.
1699
1700 The returned value will be a copy of the result of the call or a proxy to
1701 a new shared object -- see documentation for the *method_to_typeid*
1702 argument of :meth:`BaseManager.register`.
1703
Ezio Melotti1e87da12011-10-19 10:39:35 +03001704 If an exception is raised by the call, then is re-raised by
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001705 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001706 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001707 raised by :meth:`_callmethod`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001708
1709 Note in particular that an exception will be raised if *methodname* has
Martin Panter4ed35fc2015-10-10 10:52:35 +00001710 not been *exposed*.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001711
R. David Murray636b23a2009-04-28 16:08:18 +00001712 An example of the usage of :meth:`_callmethod`:
1713
1714 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001715
1716 >>> l = manager.list(range(10))
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001717 >>> l._callmethod('__len__')
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001718 10
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001719 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001720 [2, 3, 4, 5, 6]
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001721 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001722 Traceback (most recent call last):
1723 ...
1724 IndexError: list index out of range
1725
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001726 .. method:: _getvalue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001727
1728 Return a copy of the referent.
1729
1730 If the referent is unpicklable then this will raise an exception.
1731
1732 .. method:: __repr__
1733
1734 Return a representation of the proxy object.
1735
1736 .. method:: __str__
1737
1738 Return the representation of the referent.
1739
1740
1741Cleanup
1742>>>>>>>
1743
1744A proxy object uses a weakref callback so that when it gets garbage collected it
1745deregisters itself from the manager which owns its referent.
1746
1747A shared object gets deleted from the manager process when there are no longer
1748any proxies referring to it.
1749
1750
1751Process Pools
1752~~~~~~~~~~~~~
1753
1754.. module:: multiprocessing.pool
1755 :synopsis: Create pools of processes.
1756
1757One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001758with the :class:`Pool` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001759
Jesse Noller654ade32010-01-27 03:05:57 +00001760.. class:: multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001761
1762 A process pool object which controls a pool of worker processes to which jobs
1763 can be submitted. It supports asynchronous results with timeouts and
1764 callbacks and has a parallel map implementation.
1765
1766 *processes* is the number of worker processes to use. If *processes* is
1767 ``None`` then the number returned by :func:`cpu_count` is used. If
1768 *initializer* is not ``None`` then each worker process will call
1769 ``initializer(*initargs)`` when it starts.
1770
Richard Oudkerk49032532013-07-02 12:31:50 +01001771 Note that the methods of the pool object should only be called by
1772 the process which created the pool.
1773
Georg Brandl92e69722010-10-17 06:21:30 +00001774 .. versionadded:: 2.7
1775 *maxtasksperchild* is the number of tasks a worker process can complete
1776 before it will exit and be replaced with a fresh worker process, to enable
1777 unused resources to be freed. The default *maxtasksperchild* is None, which
1778 means worker processes will live as long as the pool.
Jesse Noller654ade32010-01-27 03:05:57 +00001779
1780 .. note::
1781
Georg Brandl92e69722010-10-17 06:21:30 +00001782 Worker processes within a :class:`Pool` typically live for the complete
1783 duration of the Pool's work queue. A frequent pattern found in other
1784 systems (such as Apache, mod_wsgi, etc) to free resources held by
1785 workers is to allow a worker within a pool to complete only a set
1786 amount of work before being exiting, being cleaned up and a new
1787 process spawned to replace the old one. The *maxtasksperchild*
1788 argument to the :class:`Pool` exposes this ability to the end user.
Jesse Noller654ade32010-01-27 03:05:57 +00001789
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001790 .. method:: apply(func[, args[, kwds]])
1791
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001792 Equivalent of the :func:`apply` built-in function. It blocks until the
1793 result is ready, so :meth:`apply_async` is better suited for performing
1794 work in parallel. Additionally, *func* is only executed in one of the
1795 workers of the pool.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001796
1797 .. method:: apply_async(func[, args[, kwds[, callback]]])
1798
1799 A variant of the :meth:`apply` method which returns a result object.
1800
1801 If *callback* is specified then it should be a callable which accepts a
1802 single argument. When the result becomes ready *callback* is applied to
1803 it (unless the call failed). *callback* should complete immediately since
1804 otherwise the thread which handles the results will get blocked.
1805
1806 .. method:: map(func, iterable[, chunksize])
1807
Georg Brandld7d4fd72009-07-26 14:37:28 +00001808 A parallel equivalent of the :func:`map` built-in function (it supports only
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001809 one *iterable* argument though). It blocks until the result is ready.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001810
1811 This method chops the iterable into a number of chunks which it submits to
1812 the process pool as separate tasks. The (approximate) size of these
1813 chunks can be specified by setting *chunksize* to a positive integer.
1814
Senthil Kumaran0fc13ae2011-11-03 02:02:38 +08001815 .. method:: map_async(func, iterable[, chunksize[, callback]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001816
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001817 A variant of the :meth:`.map` method which returns a result object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001818
1819 If *callback* is specified then it should be a callable which accepts a
1820 single argument. When the result becomes ready *callback* is applied to
1821 it (unless the call failed). *callback* should complete immediately since
1822 otherwise the thread which handles the results will get blocked.
1823
1824 .. method:: imap(func, iterable[, chunksize])
1825
1826 An equivalent of :func:`itertools.imap`.
1827
1828 The *chunksize* argument is the same as the one used by the :meth:`.map`
1829 method. For very long iterables using a large value for *chunksize* can
Ezio Melotti1e87da12011-10-19 10:39:35 +03001830 make the job complete **much** faster than using the default value of
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001831 ``1``.
1832
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001833 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001834 returned by the :meth:`imap` method has an optional *timeout* parameter:
1835 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1836 result cannot be returned within *timeout* seconds.
1837
1838 .. method:: imap_unordered(func, iterable[, chunksize])
1839
1840 The same as :meth:`imap` except that the ordering of the results from the
1841 returned iterator should be considered arbitrary. (Only when there is
1842 only one worker process is the order guaranteed to be "correct".)
1843
1844 .. method:: close()
1845
1846 Prevents any more tasks from being submitted to the pool. Once all the
1847 tasks have been completed the worker processes will exit.
1848
1849 .. method:: terminate()
1850
1851 Stops the worker processes immediately without completing outstanding
1852 work. When the pool object is garbage collected :meth:`terminate` will be
1853 called immediately.
1854
1855 .. method:: join()
1856
1857 Wait for the worker processes to exit. One must call :meth:`close` or
1858 :meth:`terminate` before using :meth:`join`.
1859
1860
1861.. class:: AsyncResult
1862
1863 The class of the result returned by :meth:`Pool.apply_async` and
1864 :meth:`Pool.map_async`.
1865
Jesse Nollera280fd72008-11-28 18:22:54 +00001866 .. method:: get([timeout])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001867
1868 Return the result when it arrives. If *timeout* is not ``None`` and the
1869 result does not arrive within *timeout* seconds then
1870 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1871 an exception then that exception will be reraised by :meth:`get`.
1872
1873 .. method:: wait([timeout])
1874
1875 Wait until the result is available or until *timeout* seconds pass.
1876
1877 .. method:: ready()
1878
1879 Return whether the call has completed.
1880
1881 .. method:: successful()
1882
1883 Return whether the call completed without raising an exception. Will
1884 raise :exc:`AssertionError` if the result is not ready.
1885
1886The following example demonstrates the use of a pool::
1887
1888 from multiprocessing import Pool
1889
1890 def f(x):
1891 return x*x
1892
1893 if __name__ == '__main__':
1894 pool = Pool(processes=4) # start 4 worker processes
1895
Jesse Nollera280fd72008-11-28 18:22:54 +00001896 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001897 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
1898
1899 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
1900
1901 it = pool.imap(f, range(10))
1902 print it.next() # prints "0"
1903 print it.next() # prints "1"
1904 print it.next(timeout=1) # prints "4" unless your computer is *very* slow
1905
1906 import time
Jesse Nollera280fd72008-11-28 18:22:54 +00001907 result = pool.apply_async(time.sleep, (10,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001908 print result.get(timeout=1) # raises TimeoutError
1909
1910
1911.. _multiprocessing-listeners-clients:
1912
1913Listeners and Clients
1914~~~~~~~~~~~~~~~~~~~~~
1915
1916.. module:: multiprocessing.connection
1917 :synopsis: API for dealing with sockets.
1918
1919Usually message passing between processes is done using queues or by using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001920:class:`~multiprocessing.Connection` objects returned by
1921:func:`~multiprocessing.Pipe`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001922
1923However, the :mod:`multiprocessing.connection` module allows some extra
1924flexibility. It basically gives a high level message oriented API for dealing
1925with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001926authentication* using the :mod:`hmac` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001927
1928
1929.. function:: deliver_challenge(connection, authkey)
1930
1931 Send a randomly generated message to the other end of the connection and wait
1932 for a reply.
1933
1934 If the reply matches the digest of the message using *authkey* as the key
1935 then a welcome message is sent to the other end of the connection. Otherwise
1936 :exc:`AuthenticationError` is raised.
1937
Ezio Melotti3218f652013-04-10 17:59:20 +03001938.. function:: answer_challenge(connection, authkey)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001939
1940 Receive a message, calculate the digest of the message using *authkey* as the
1941 key, and then send the digest back.
1942
1943 If a welcome message is not received, then :exc:`AuthenticationError` is
1944 raised.
1945
1946.. function:: Client(address[, family[, authenticate[, authkey]]])
1947
1948 Attempt to set up a connection to the listener which is using address
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001949 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001950
1951 The type of the connection is determined by *family* argument, but this can
1952 generally be omitted since it can usually be inferred from the format of
1953 *address*. (See :ref:`multiprocessing-address-formats`)
1954
Jesse Noller34116922009-06-29 18:24:26 +00001955 If *authenticate* is ``True`` or *authkey* is a string then digest
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001956 authentication is used. The key used for authentication will be either
Benjamin Peterson73641d72008-08-20 14:07:59 +00001957 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001958 If authentication fails then :exc:`AuthenticationError` is raised. See
1959 :ref:`multiprocessing-auth-keys`.
1960
1961.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1962
1963 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1964 connections.
1965
1966 *address* is the address to be used by the bound socket or named pipe of the
1967 listener object.
1968
Jesse Nollerb12e79d2009-04-01 16:42:19 +00001969 .. note::
1970
1971 If an address of '0.0.0.0' is used, the address will not be a connectable
1972 end point on Windows. If you require a connectable end-point,
1973 you should use '127.0.0.1'.
1974
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001975 *family* is the type of socket (or named pipe) to use. This can be one of
1976 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1977 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1978 the first is guaranteed to be available. If *family* is ``None`` then the
1979 family is inferred from the format of *address*. If *address* is also
1980 ``None`` then a default is chosen. This default is the family which is
1981 assumed to be the fastest available. See
1982 :ref:`multiprocessing-address-formats`. Note that if *family* is
1983 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1984 private temporary directory created using :func:`tempfile.mkstemp`.
1985
1986 If the listener object uses a socket then *backlog* (1 by default) is passed
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001987 to the :meth:`~socket.socket.listen` method of the socket once it has been
1988 bound.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001989
1990 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1991 ``None`` then digest authentication is used.
1992
1993 If *authkey* is a string then it will be used as the authentication key;
1994 otherwise it must be *None*.
1995
1996 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001997 ``current_process().authkey`` is used as the authentication key. If
Jesse Noller34116922009-06-29 18:24:26 +00001998 *authkey* is ``None`` and *authenticate* is ``False`` then no
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001999 authentication is done. If authentication fails then
2000 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
2001
2002 .. method:: accept()
2003
2004 Accept a connection on the bound socket or named pipe of the listener
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002005 object and return a :class:`~multiprocessing.Connection` object. If
2006 authentication is attempted and fails, then
2007 :exc:`~multiprocessing.AuthenticationError` is raised.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002008
2009 .. method:: close()
2010
2011 Close the bound socket or named pipe of the listener object. This is
2012 called automatically when the listener is garbage collected. However it
2013 is advisable to call it explicitly.
2014
2015 Listener objects have the following read-only properties:
2016
2017 .. attribute:: address
2018
2019 The address which is being used by the Listener object.
2020
2021 .. attribute:: last_accepted
2022
2023 The address from which the last accepted connection came. If this is
2024 unavailable then it is ``None``.
2025
2026
2027The module defines two exceptions:
2028
2029.. exception:: AuthenticationError
2030
2031 Exception raised when there is an authentication error.
2032
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002033
2034**Examples**
2035
2036The following server code creates a listener which uses ``'secret password'`` as
2037an authentication key. It then waits for a connection and sends some data to
2038the client::
2039
2040 from multiprocessing.connection import Listener
2041 from array import array
2042
2043 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
2044 listener = Listener(address, authkey='secret password')
2045
2046 conn = listener.accept()
2047 print 'connection accepted from', listener.last_accepted
2048
2049 conn.send([2.25, None, 'junk', float])
2050
2051 conn.send_bytes('hello')
2052
2053 conn.send_bytes(array('i', [42, 1729]))
2054
2055 conn.close()
2056 listener.close()
2057
2058The following code connects to the server and receives some data from the
2059server::
2060
2061 from multiprocessing.connection import Client
2062 from array import array
2063
2064 address = ('localhost', 6000)
2065 conn = Client(address, authkey='secret password')
2066
2067 print conn.recv() # => [2.25, None, 'junk', float]
2068
2069 print conn.recv_bytes() # => 'hello'
2070
2071 arr = array('i', [0, 0, 0, 0, 0])
2072 print conn.recv_bytes_into(arr) # => 8
2073 print arr # => array('i', [42, 1729, 0, 0, 0])
2074
2075 conn.close()
2076
2077
2078.. _multiprocessing-address-formats:
2079
2080Address Formats
2081>>>>>>>>>>>>>>>
2082
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002083* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002084 *hostname* is a string and *port* is an integer.
2085
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002086* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002087 filesystem.
2088
2089* An ``'AF_PIPE'`` address is a string of the form
Georg Brandl6b28f392008-12-27 19:06:04 +00002090 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandlfc29f272009-01-02 20:25:14 +00002091 pipe on a remote computer called *ServerName* one should use an address of the
Georg Brandldd7e3132009-01-04 10:24:09 +00002092 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002093
2094Note that any string beginning with two backslashes is assumed by default to be
2095an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
2096
2097
2098.. _multiprocessing-auth-keys:
2099
2100Authentication keys
2101~~~~~~~~~~~~~~~~~~~
2102
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002103When one uses :meth:`Connection.recv <multiprocessing.Connection.recv>`, the
2104data received is automatically
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002105unpickled. Unfortunately unpickling data from an untrusted source is a security
2106risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
2107to provide digest authentication.
2108
2109An authentication key is a string which can be thought of as a password: once a
2110connection is established both ends will demand proof that the other knows the
2111authentication key. (Demonstrating that both ends are using the same key does
2112**not** involve sending the key over the connection.)
2113
2114If authentication is requested but do authentication key is specified then the
Benjamin Peterson73641d72008-08-20 14:07:59 +00002115return value of ``current_process().authkey`` is used (see
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002116:class:`~multiprocessing.Process`). This value will automatically inherited by
2117any :class:`~multiprocessing.Process` object that the current process creates.
2118This means that (by default) all processes of a multi-process program will share
2119a single authentication key which can be used when setting up connections
Andrew M. Kuchlinga178a692009-04-03 21:45:29 +00002120between themselves.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002121
2122Suitable authentication keys can also be generated by using :func:`os.urandom`.
2123
2124
2125Logging
2126~~~~~~~
2127
2128Some support for logging is available. Note, however, that the :mod:`logging`
2129package does not use process shared locks so it is possible (depending on the
2130handler type) for messages from different processes to get mixed up.
2131
2132.. currentmodule:: multiprocessing
2133.. function:: get_logger()
2134
2135 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
2136 will be created.
2137
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002138 When first created the logger has level :data:`logging.NOTSET` and no
2139 default handler. Messages sent to this logger will not by default propagate
2140 to the root logger.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002141
2142 Note that on Windows child processes will only inherit the level of the
2143 parent process's logger -- any other customization of the logger will not be
2144 inherited.
2145
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002146.. currentmodule:: multiprocessing
2147.. function:: log_to_stderr()
2148
2149 This function performs a call to :func:`get_logger` but in addition to
2150 returning the logger created by get_logger, it adds a handler which sends
2151 output to :data:`sys.stderr` using format
2152 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2153
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002154Below is an example session with logging turned on::
2155
Georg Brandl19cc9442008-10-16 21:36:39 +00002156 >>> import multiprocessing, logging
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002157 >>> logger = multiprocessing.log_to_stderr()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002158 >>> logger.setLevel(logging.INFO)
2159 >>> logger.warning('doomed')
2160 [WARNING/MainProcess] doomed
Georg Brandl19cc9442008-10-16 21:36:39 +00002161 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002162 [INFO/SyncManager-...] child process calling self.run()
2163 [INFO/SyncManager-...] created temp directory /.../pymp-...
2164 [INFO/SyncManager-...] manager serving at '/.../listener-...'
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002165 >>> del m
2166 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002167 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002168
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002169In addition to having these two logging functions, the multiprocessing also
2170exposes two additional logging level attributes. These are :const:`SUBWARNING`
2171and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
2172normal level hierarchy.
2173
2174+----------------+----------------+
2175| Level | Numeric value |
2176+================+================+
2177| ``SUBWARNING`` | 25 |
2178+----------------+----------------+
2179| ``SUBDEBUG`` | 5 |
2180+----------------+----------------+
2181
2182For a full table of logging levels, see the :mod:`logging` module.
2183
2184These additional logging levels are used primarily for certain debug messages
2185within the multiprocessing module. Below is the same example as above, except
2186with :const:`SUBDEBUG` enabled::
2187
2188 >>> import multiprocessing, logging
2189 >>> logger = multiprocessing.log_to_stderr()
2190 >>> logger.setLevel(multiprocessing.SUBDEBUG)
2191 >>> logger.warning('doomed')
2192 [WARNING/MainProcess] doomed
2193 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002194 [INFO/SyncManager-...] child process calling self.run()
2195 [INFO/SyncManager-...] created temp directory /.../pymp-...
2196 [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002197 >>> del m
2198 [SUBDEBUG/MainProcess] finalizer calling ...
2199 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002200 [DEBUG/SyncManager-...] manager received shutdown message
2201 [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
2202 [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
2203 [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
2204 [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
2205 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002206
2207The :mod:`multiprocessing.dummy` module
2208~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2209
2210.. module:: multiprocessing.dummy
2211 :synopsis: Dumb wrapper around threading.
2212
2213:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002214no more than a wrapper around the :mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002215
2216
2217.. _multiprocessing-programming:
2218
2219Programming guidelines
2220----------------------
2221
2222There are certain guidelines and idioms which should be adhered to when using
2223:mod:`multiprocessing`.
2224
2225
2226All platforms
2227~~~~~~~~~~~~~
2228
2229Avoid shared state
2230
2231 As far as possible one should try to avoid shifting large amounts of data
2232 between processes.
2233
2234 It is probably best to stick to using queues or pipes for communication
2235 between processes rather than using the lower level synchronization
2236 primitives from the :mod:`threading` module.
2237
2238Picklability
2239
2240 Ensure that the arguments to the methods of proxies are picklable.
2241
2242Thread safety of proxies
2243
2244 Do not use a proxy object from more than one thread unless you protect it
2245 with a lock.
2246
2247 (There is never a problem with different processes using the *same* proxy.)
2248
2249Joining zombie processes
2250
2251 On Unix when a process finishes but has not been joined it becomes a zombie.
2252 There should never be very many because each time a new process starts (or
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002253 :func:`~multiprocessing.active_children` is called) all completed processes
2254 which have not yet been joined will be joined. Also calling a finished
2255 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
2256 join the process. Even so it is probably good
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002257 practice to explicitly join all the processes that you start.
2258
2259Better to inherit than pickle/unpickle
2260
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002261 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002262 that child processes can use them. However, one should generally avoid
2263 sending shared objects to other processes using pipes or queues. Instead
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002264 you should arrange the program so that a process which needs access to a
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002265 shared resource created elsewhere can inherit it from an ancestor process.
2266
2267Avoid terminating processes
2268
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002269 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
2270 method to stop a process is liable to
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002271 cause any shared resources (such as locks, semaphores, pipes and queues)
2272 currently being used by the process to become broken or unavailable to other
2273 processes.
2274
2275 Therefore it is probably best to only consider using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002276 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
2277 which never use any shared resources.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002278
2279Joining processes that use queues
2280
2281 Bear in mind that a process that has put items in a queue will wait before
2282 terminating until all the buffered items are fed by the "feeder" thread to
2283 the underlying pipe. (The child process can call the
Sandro Tosi8b48c662012-02-25 19:35:16 +01002284 :meth:`~multiprocessing.Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002285
2286 This means that whenever you use a queue you need to make sure that all
2287 items which have been put on the queue will eventually be removed before the
2288 process is joined. Otherwise you cannot be sure that processes which have
2289 put items on the queue will terminate. Remember also that non-daemonic
Zachary Ware06b74a72014-10-03 10:55:12 -05002290 processes will be joined automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002291
2292 An example which will deadlock is the following::
2293
2294 from multiprocessing import Process, Queue
2295
2296 def f(q):
2297 q.put('X' * 1000000)
2298
2299 if __name__ == '__main__':
2300 queue = Queue()
2301 p = Process(target=f, args=(queue,))
2302 p.start()
2303 p.join() # this deadlocks
2304 obj = queue.get()
2305
Zachary Ware06b74a72014-10-03 10:55:12 -05002306 A fix here would be to swap the last two lines (or simply remove the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002307 ``p.join()`` line).
2308
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002309Explicitly pass resources to child processes
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002310
2311 On Unix a child process can make use of a shared resource created in a
2312 parent process using a global resource. However, it is better to pass the
2313 object as an argument to the constructor for the child process.
2314
2315 Apart from making the code (potentially) compatible with Windows this also
2316 ensures that as long as the child process is still alive the object will not
2317 be garbage collected in the parent process. This might be important if some
2318 resource is freed when the object is garbage collected in the parent
2319 process.
2320
2321 So for instance ::
2322
2323 from multiprocessing import Process, Lock
2324
2325 def f():
2326 ... do something using "lock" ...
2327
2328 if __name__ == '__main__':
2329 lock = Lock()
2330 for i in range(10):
2331 Process(target=f).start()
2332
2333 should be rewritten as ::
2334
2335 from multiprocessing import Process, Lock
2336
2337 def f(l):
2338 ... do something using "l" ...
2339
2340 if __name__ == '__main__':
2341 lock = Lock()
2342 for i in range(10):
2343 Process(target=f, args=(lock,)).start()
2344
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002345Beware of replacing :data:`sys.stdin` with a "file like object"
Jesse Noller1b90efb2009-06-30 17:11:52 +00002346
2347 :mod:`multiprocessing` originally unconditionally called::
2348
2349 os.close(sys.stdin.fileno())
2350
R. David Murray321afa82009-07-01 02:49:10 +00002351 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
Jesse Noller1b90efb2009-06-30 17:11:52 +00002352 in issues with processes-in-processes. This has been changed to::
2353
2354 sys.stdin.close()
2355 sys.stdin = open(os.devnull)
2356
2357 Which solves the fundamental issue of processes colliding with each other
2358 resulting in a bad file descriptor error, but introduces a potential danger
2359 to applications which replace :func:`sys.stdin` with a "file-like object"
R. David Murray321afa82009-07-01 02:49:10 +00002360 with output buffering. This danger is that if multiple processes call
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002361 :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
Jesse Noller1b90efb2009-06-30 17:11:52 +00002362 data being flushed to the object multiple times, resulting in corruption.
2363
2364 If you write a file-like object and implement your own caching, you can
2365 make it fork-safe by storing the pid whenever you append to the cache,
2366 and discarding the cache when the pid changes. For example::
2367
2368 @property
2369 def cache(self):
2370 pid = os.getpid()
2371 if pid != self._pid:
2372 self._pid = pid
2373 self._cache = []
2374 return self._cache
2375
2376 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002377
2378Windows
2379~~~~~~~
2380
2381Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2382
2383More picklability
2384
2385 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2386 means, in particular, that bound or unbound methods cannot be used directly
2387 as the ``target`` argument on Windows --- just define a function and use
2388 that instead.
2389
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002390 Also, if you subclass :class:`~multiprocessing.Process` then make sure that
2391 instances will be picklable when the :meth:`Process.start
2392 <multiprocessing.Process.start>` method is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002393
2394Global variables
2395
2396 Bear in mind that if code run in a child process tries to access a global
2397 variable, then the value it sees (if any) may not be the same as the value
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002398 in the parent process at the time that :meth:`Process.start
2399 <multiprocessing.Process.start>` was called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002400
2401 However, global variables which are just module level constants cause no
2402 problems.
2403
2404Safe importing of main module
2405
2406 Make sure that the main module can be safely imported by a new Python
2407 interpreter without causing unintended side effects (such a starting a new
2408 process).
2409
2410 For example, under Windows running the following module would fail with a
2411 :exc:`RuntimeError`::
2412
2413 from multiprocessing import Process
2414
2415 def foo():
2416 print 'hello'
2417
2418 p = Process(target=foo)
2419 p.start()
2420
2421 Instead one should protect the "entry point" of the program by using ``if
2422 __name__ == '__main__':`` as follows::
2423
2424 from multiprocessing import Process, freeze_support
2425
2426 def foo():
2427 print 'hello'
2428
2429 if __name__ == '__main__':
2430 freeze_support()
2431 p = Process(target=foo)
2432 p.start()
2433
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002434 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002435 normally instead of frozen.)
2436
2437 This allows the newly spawned Python interpreter to safely import the module
2438 and then run the module's ``foo()`` function.
2439
2440 Similar restrictions apply if a pool or manager is created in the main
2441 module.
2442
2443
2444.. _multiprocessing-examples:
2445
2446Examples
2447--------
2448
2449Demonstration of how to create and use customized managers and proxies:
2450
2451.. literalinclude:: ../includes/mp_newtype.py
2452
2453
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002454Using :class:`~multiprocessing.pool.Pool`:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002455
2456.. literalinclude:: ../includes/mp_pool.py
2457
2458
2459Synchronization types like locks, conditions and queues:
2460
2461.. literalinclude:: ../includes/mp_synchronize.py
2462
2463
Georg Brandl21946af2010-10-06 09:28:45 +00002464An example showing how to use queues to feed tasks to a collection of worker
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002465processes and collect the results:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002466
2467.. literalinclude:: ../includes/mp_workers.py
2468
2469
2470An example of how a pool of worker processes can each run a
2471:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2472socket.
2473
2474.. literalinclude:: ../includes/mp_webserver.py
2475
2476
2477Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2478
2479.. literalinclude:: ../includes/mp_benchmarks.py
2480