blob: 0df48cd690826f6045dbbb8bf3ed9f9b8de11456 [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`,
Senthil Kumaran762d7612016-01-20 03:18:48 -0800218 :class:`dict`, :class:`~managers.Namespace`, :class:`Lock`, :class:`RLock`,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000219 :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
Senthil Kumaran762d7612016-01-20 03:18:48 -08001515.. class:: Namespace
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001516
Senthil Kumaran762d7612016-01-20 03:18:48 -08001517 A type that can register with :class:`SyncManager`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001518
Senthil Kumaran762d7612016-01-20 03:18:48 -08001519 A namespace object has no public methods, but does have writable attributes.
1520 Its representation shows the values of its attributes.
R. David Murray636b23a2009-04-28 16:08:18 +00001521
Senthil Kumaran762d7612016-01-20 03:18:48 -08001522 However, when using a proxy for a namespace object, an attribute beginning with
1523 ``'_'`` will be an attribute of the proxy and not an attribute of the referent:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001524
Senthil Kumaran762d7612016-01-20 03:18:48 -08001525 .. doctest::
1526
1527 >>> manager = multiprocessing.Manager()
1528 >>> Global = manager.Namespace()
1529 >>> Global.x = 10
1530 >>> Global.y = 'hello'
1531 >>> Global._z = 12.3 # this is an attribute of the proxy
1532 >>> print Global
1533 Namespace(x=10, y='hello')
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001534
1535
1536Customized managers
1537>>>>>>>>>>>>>>>>>>>
1538
1539To create one's own manager, one creates a subclass of :class:`BaseManager` and
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001540uses the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001541callables with the manager class. For example::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001542
1543 from multiprocessing.managers import BaseManager
1544
1545 class MathsClass(object):
1546 def add(self, x, y):
1547 return x + y
1548 def mul(self, x, y):
1549 return x * y
1550
1551 class MyManager(BaseManager):
1552 pass
1553
1554 MyManager.register('Maths', MathsClass)
1555
1556 if __name__ == '__main__':
1557 manager = MyManager()
1558 manager.start()
1559 maths = manager.Maths()
1560 print maths.add(4, 3) # prints 7
1561 print maths.mul(7, 8) # prints 56
1562
1563
1564Using a remote manager
1565>>>>>>>>>>>>>>>>>>>>>>
1566
1567It is possible to run a manager server on one machine and have clients use it
1568from other machines (assuming that the firewalls involved allow it).
1569
1570Running the following commands creates a server for a single shared queue which
1571remote clients can access::
1572
1573 >>> from multiprocessing.managers import BaseManager
1574 >>> import Queue
1575 >>> queue = Queue.Queue()
1576 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001577 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001578 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Nollera280fd72008-11-28 18:22:54 +00001579 >>> s = m.get_server()
R. David Murray636b23a2009-04-28 16:08:18 +00001580 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001581
1582One client can access the server as follows::
1583
1584 >>> from multiprocessing.managers import BaseManager
1585 >>> class QueueManager(BaseManager): pass
Jesse Nollera280fd72008-11-28 18:22:54 +00001586 >>> QueueManager.register('get_queue')
1587 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1588 >>> m.connect()
1589 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001590 >>> queue.put('hello')
1591
1592Another client can also use it::
1593
1594 >>> from multiprocessing.managers import BaseManager
1595 >>> class QueueManager(BaseManager): pass
R. David Murray636b23a2009-04-28 16:08:18 +00001596 >>> QueueManager.register('get_queue')
1597 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1598 >>> m.connect()
1599 >>> queue = m.get_queue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001600 >>> queue.get()
1601 'hello'
1602
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001603Local processes can also access that queue, using the code from above on the
Jesse Nollera280fd72008-11-28 18:22:54 +00001604client to access it remotely::
1605
1606 >>> from multiprocessing import Process, Queue
1607 >>> from multiprocessing.managers import BaseManager
1608 >>> class Worker(Process):
1609 ... def __init__(self, q):
1610 ... self.q = q
1611 ... super(Worker, self).__init__()
1612 ... def run(self):
1613 ... self.q.put('local hello')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001614 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001615 >>> queue = Queue()
1616 >>> w = Worker(queue)
1617 >>> w.start()
1618 >>> class QueueManager(BaseManager): pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001619 ...
Jesse Nollera280fd72008-11-28 18:22:54 +00001620 >>> QueueManager.register('get_queue', callable=lambda: queue)
1621 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1622 >>> s = m.get_server()
1623 >>> s.serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001624
1625Proxy Objects
1626~~~~~~~~~~~~~
1627
1628A proxy is an object which *refers* to a shared object which lives (presumably)
1629in a different process. The shared object is said to be the *referent* of the
1630proxy. Multiple proxy objects may have the same referent.
1631
1632A proxy object has methods which invoke corresponding methods of its referent
1633(although not every method of the referent will necessarily be available through
1634the proxy). A proxy can usually be used in most of the same ways that its
R. David Murray636b23a2009-04-28 16:08:18 +00001635referent can:
1636
1637.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001638
1639 >>> from multiprocessing import Manager
1640 >>> manager = Manager()
1641 >>> l = manager.list([i*i for i in range(10)])
1642 >>> print l
1643 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1644 >>> print repr(l)
R. David Murray636b23a2009-04-28 16:08:18 +00001645 <ListProxy object, typeid 'list' at 0x...>
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001646 >>> l[4]
1647 16
1648 >>> l[2:5]
1649 [4, 9, 16]
1650
1651Notice that applying :func:`str` to a proxy will return the representation of
1652the referent, whereas applying :func:`repr` will return the representation of
1653the proxy.
1654
1655An important feature of proxy objects is that they are picklable so they can be
1656passed between processes. Note, however, that if a proxy is sent to the
1657corresponding manager's process then unpickling it will produce the referent
R. David Murray636b23a2009-04-28 16:08:18 +00001658itself. This means, for example, that one shared object can contain a second:
1659
1660.. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001661
1662 >>> a = manager.list()
1663 >>> b = manager.list()
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001664 >>> a.append(b) # referent of a now contains referent of b
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001665 >>> print a, b
1666 [[]] []
1667 >>> b.append('hello')
1668 >>> print a, b
1669 [['hello']] ['hello']
1670
1671.. note::
1672
1673 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
R. David Murray636b23a2009-04-28 16:08:18 +00001674 by value. So, for instance, we have:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001675
R. David Murray636b23a2009-04-28 16:08:18 +00001676 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001677
R. David Murray636b23a2009-04-28 16:08:18 +00001678 >>> manager.list([1,2,3]) == [1,2,3]
1679 False
1680
1681 One should just use a copy of the referent instead when making comparisons.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001682
1683.. class:: BaseProxy
1684
1685 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1686
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001687 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001688
1689 Call and return the result of a method of the proxy's referent.
1690
1691 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1692
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001693 proxy._callmethod(methodname, args, kwds)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001694
1695 will evaluate the expression ::
1696
1697 getattr(obj, methodname)(*args, **kwds)
1698
1699 in the manager's process.
1700
1701 The returned value will be a copy of the result of the call or a proxy to
1702 a new shared object -- see documentation for the *method_to_typeid*
1703 argument of :meth:`BaseManager.register`.
1704
Ezio Melotti1e87da12011-10-19 10:39:35 +03001705 If an exception is raised by the call, then is re-raised by
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001706 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001707 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001708 raised by :meth:`_callmethod`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001709
1710 Note in particular that an exception will be raised if *methodname* has
Martin Panter4ed35fc2015-10-10 10:52:35 +00001711 not been *exposed*.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001712
R. David Murray636b23a2009-04-28 16:08:18 +00001713 An example of the usage of :meth:`_callmethod`:
1714
1715 .. doctest::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001716
1717 >>> l = manager.list(range(10))
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001718 >>> l._callmethod('__len__')
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001719 10
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001720 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001721 [2, 3, 4, 5, 6]
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001722 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001723 Traceback (most recent call last):
1724 ...
1725 IndexError: list index out of range
1726
Benjamin Peterson2b97b712008-12-19 02:31:35 +00001727 .. method:: _getvalue()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001728
1729 Return a copy of the referent.
1730
1731 If the referent is unpicklable then this will raise an exception.
1732
1733 .. method:: __repr__
1734
1735 Return a representation of the proxy object.
1736
1737 .. method:: __str__
1738
1739 Return the representation of the referent.
1740
1741
1742Cleanup
1743>>>>>>>
1744
1745A proxy object uses a weakref callback so that when it gets garbage collected it
1746deregisters itself from the manager which owns its referent.
1747
1748A shared object gets deleted from the manager process when there are no longer
1749any proxies referring to it.
1750
1751
1752Process Pools
1753~~~~~~~~~~~~~
1754
1755.. module:: multiprocessing.pool
1756 :synopsis: Create pools of processes.
1757
1758One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001759with the :class:`Pool` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001760
Jesse Noller654ade32010-01-27 03:05:57 +00001761.. class:: multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001762
1763 A process pool object which controls a pool of worker processes to which jobs
1764 can be submitted. It supports asynchronous results with timeouts and
1765 callbacks and has a parallel map implementation.
1766
1767 *processes* is the number of worker processes to use. If *processes* is
1768 ``None`` then the number returned by :func:`cpu_count` is used. If
1769 *initializer* is not ``None`` then each worker process will call
1770 ``initializer(*initargs)`` when it starts.
1771
Richard Oudkerk49032532013-07-02 12:31:50 +01001772 Note that the methods of the pool object should only be called by
1773 the process which created the pool.
1774
Georg Brandl92e69722010-10-17 06:21:30 +00001775 .. versionadded:: 2.7
1776 *maxtasksperchild* is the number of tasks a worker process can complete
1777 before it will exit and be replaced with a fresh worker process, to enable
1778 unused resources to be freed. The default *maxtasksperchild* is None, which
1779 means worker processes will live as long as the pool.
Jesse Noller654ade32010-01-27 03:05:57 +00001780
1781 .. note::
1782
Georg Brandl92e69722010-10-17 06:21:30 +00001783 Worker processes within a :class:`Pool` typically live for the complete
1784 duration of the Pool's work queue. A frequent pattern found in other
1785 systems (such as Apache, mod_wsgi, etc) to free resources held by
1786 workers is to allow a worker within a pool to complete only a set
1787 amount of work before being exiting, being cleaned up and a new
1788 process spawned to replace the old one. The *maxtasksperchild*
1789 argument to the :class:`Pool` exposes this ability to the end user.
Jesse Noller654ade32010-01-27 03:05:57 +00001790
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001791 .. method:: apply(func[, args[, kwds]])
1792
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001793 Equivalent of the :func:`apply` built-in function. It blocks until the
1794 result is ready, so :meth:`apply_async` is better suited for performing
1795 work in parallel. Additionally, *func* is only executed in one of the
1796 workers of the pool.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001797
1798 .. method:: apply_async(func[, args[, kwds[, callback]]])
1799
1800 A variant of the :meth:`apply` method which returns a result object.
1801
1802 If *callback* is specified then it should be a callable which accepts a
1803 single argument. When the result becomes ready *callback* is applied to
1804 it (unless the call failed). *callback* should complete immediately since
1805 otherwise the thread which handles the results will get blocked.
1806
1807 .. method:: map(func, iterable[, chunksize])
1808
Georg Brandld7d4fd72009-07-26 14:37:28 +00001809 A parallel equivalent of the :func:`map` built-in function (it supports only
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02001810 one *iterable* argument though). It blocks until the result is ready.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001811
1812 This method chops the iterable into a number of chunks which it submits to
1813 the process pool as separate tasks. The (approximate) size of these
1814 chunks can be specified by setting *chunksize* to a positive integer.
1815
Senthil Kumaran0fc13ae2011-11-03 02:02:38 +08001816 .. method:: map_async(func, iterable[, chunksize[, callback]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001817
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001818 A variant of the :meth:`.map` method which returns a result object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001819
1820 If *callback* is specified then it should be a callable which accepts a
1821 single argument. When the result becomes ready *callback* is applied to
1822 it (unless the call failed). *callback* should complete immediately since
1823 otherwise the thread which handles the results will get blocked.
1824
1825 .. method:: imap(func, iterable[, chunksize])
1826
1827 An equivalent of :func:`itertools.imap`.
1828
1829 The *chunksize* argument is the same as the one used by the :meth:`.map`
1830 method. For very long iterables using a large value for *chunksize* can
Ezio Melotti1e87da12011-10-19 10:39:35 +03001831 make the job complete **much** faster than using the default value of
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001832 ``1``.
1833
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001834 Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001835 returned by the :meth:`imap` method has an optional *timeout* parameter:
1836 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1837 result cannot be returned within *timeout* seconds.
1838
1839 .. method:: imap_unordered(func, iterable[, chunksize])
1840
1841 The same as :meth:`imap` except that the ordering of the results from the
1842 returned iterator should be considered arbitrary. (Only when there is
1843 only one worker process is the order guaranteed to be "correct".)
1844
1845 .. method:: close()
1846
1847 Prevents any more tasks from being submitted to the pool. Once all the
1848 tasks have been completed the worker processes will exit.
1849
1850 .. method:: terminate()
1851
1852 Stops the worker processes immediately without completing outstanding
1853 work. When the pool object is garbage collected :meth:`terminate` will be
1854 called immediately.
1855
1856 .. method:: join()
1857
1858 Wait for the worker processes to exit. One must call :meth:`close` or
1859 :meth:`terminate` before using :meth:`join`.
1860
1861
1862.. class:: AsyncResult
1863
1864 The class of the result returned by :meth:`Pool.apply_async` and
1865 :meth:`Pool.map_async`.
1866
Jesse Nollera280fd72008-11-28 18:22:54 +00001867 .. method:: get([timeout])
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001868
1869 Return the result when it arrives. If *timeout* is not ``None`` and the
1870 result does not arrive within *timeout* seconds then
1871 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1872 an exception then that exception will be reraised by :meth:`get`.
1873
1874 .. method:: wait([timeout])
1875
1876 Wait until the result is available or until *timeout* seconds pass.
1877
1878 .. method:: ready()
1879
1880 Return whether the call has completed.
1881
1882 .. method:: successful()
1883
1884 Return whether the call completed without raising an exception. Will
1885 raise :exc:`AssertionError` if the result is not ready.
1886
1887The following example demonstrates the use of a pool::
1888
1889 from multiprocessing import Pool
1890
1891 def f(x):
1892 return x*x
1893
1894 if __name__ == '__main__':
1895 pool = Pool(processes=4) # start 4 worker processes
1896
Jesse Nollera280fd72008-11-28 18:22:54 +00001897 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001898 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
1899
1900 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
1901
1902 it = pool.imap(f, range(10))
1903 print it.next() # prints "0"
1904 print it.next() # prints "1"
1905 print it.next(timeout=1) # prints "4" unless your computer is *very* slow
1906
1907 import time
Jesse Nollera280fd72008-11-28 18:22:54 +00001908 result = pool.apply_async(time.sleep, (10,))
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001909 print result.get(timeout=1) # raises TimeoutError
1910
1911
1912.. _multiprocessing-listeners-clients:
1913
1914Listeners and Clients
1915~~~~~~~~~~~~~~~~~~~~~
1916
1917.. module:: multiprocessing.connection
1918 :synopsis: API for dealing with sockets.
1919
1920Usually message passing between processes is done using queues or by using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001921:class:`~multiprocessing.Connection` objects returned by
1922:func:`~multiprocessing.Pipe`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001923
1924However, the :mod:`multiprocessing.connection` module allows some extra
1925flexibility. It basically gives a high level message oriented API for dealing
1926with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001927authentication* using the :mod:`hmac` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001928
1929
1930.. function:: deliver_challenge(connection, authkey)
1931
1932 Send a randomly generated message to the other end of the connection and wait
1933 for a reply.
1934
1935 If the reply matches the digest of the message using *authkey* as the key
1936 then a welcome message is sent to the other end of the connection. Otherwise
1937 :exc:`AuthenticationError` is raised.
1938
Ezio Melotti3218f652013-04-10 17:59:20 +03001939.. function:: answer_challenge(connection, authkey)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001940
1941 Receive a message, calculate the digest of the message using *authkey* as the
1942 key, and then send the digest back.
1943
1944 If a welcome message is not received, then :exc:`AuthenticationError` is
1945 raised.
1946
1947.. function:: Client(address[, family[, authenticate[, authkey]]])
1948
1949 Attempt to set up a connection to the listener which is using address
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001950 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001951
1952 The type of the connection is determined by *family* argument, but this can
1953 generally be omitted since it can usually be inferred from the format of
1954 *address*. (See :ref:`multiprocessing-address-formats`)
1955
Jesse Noller34116922009-06-29 18:24:26 +00001956 If *authenticate* is ``True`` or *authkey* is a string then digest
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001957 authentication is used. The key used for authentication will be either
Benjamin Peterson73641d72008-08-20 14:07:59 +00001958 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001959 If authentication fails then :exc:`AuthenticationError` is raised. See
1960 :ref:`multiprocessing-auth-keys`.
1961
1962.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1963
1964 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1965 connections.
1966
1967 *address* is the address to be used by the bound socket or named pipe of the
1968 listener object.
1969
Jesse Nollerb12e79d2009-04-01 16:42:19 +00001970 .. note::
1971
1972 If an address of '0.0.0.0' is used, the address will not be a connectable
1973 end point on Windows. If you require a connectable end-point,
1974 you should use '127.0.0.1'.
1975
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001976 *family* is the type of socket (or named pipe) to use. This can be one of
1977 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1978 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1979 the first is guaranteed to be available. If *family* is ``None`` then the
1980 family is inferred from the format of *address*. If *address* is also
1981 ``None`` then a default is chosen. This default is the family which is
1982 assumed to be the fastest available. See
1983 :ref:`multiprocessing-address-formats`. Note that if *family* is
1984 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1985 private temporary directory created using :func:`tempfile.mkstemp`.
1986
1987 If the listener object uses a socket then *backlog* (1 by default) is passed
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03001988 to the :meth:`~socket.socket.listen` method of the socket once it has been
1989 bound.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001990
1991 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1992 ``None`` then digest authentication is used.
1993
1994 If *authkey* is a string then it will be used as the authentication key;
1995 otherwise it must be *None*.
1996
1997 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001998 ``current_process().authkey`` is used as the authentication key. If
Jesse Noller34116922009-06-29 18:24:26 +00001999 *authkey* is ``None`` and *authenticate* is ``False`` then no
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002000 authentication is done. If authentication fails then
2001 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
2002
2003 .. method:: accept()
2004
2005 Accept a connection on the bound socket or named pipe of the listener
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002006 object and return a :class:`~multiprocessing.Connection` object. If
2007 authentication is attempted and fails, then
2008 :exc:`~multiprocessing.AuthenticationError` is raised.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002009
2010 .. method:: close()
2011
2012 Close the bound socket or named pipe of the listener object. This is
2013 called automatically when the listener is garbage collected. However it
2014 is advisable to call it explicitly.
2015
2016 Listener objects have the following read-only properties:
2017
2018 .. attribute:: address
2019
2020 The address which is being used by the Listener object.
2021
2022 .. attribute:: last_accepted
2023
2024 The address from which the last accepted connection came. If this is
2025 unavailable then it is ``None``.
2026
2027
2028The module defines two exceptions:
2029
2030.. exception:: AuthenticationError
2031
2032 Exception raised when there is an authentication error.
2033
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002034
2035**Examples**
2036
2037The following server code creates a listener which uses ``'secret password'`` as
2038an authentication key. It then waits for a connection and sends some data to
2039the client::
2040
2041 from multiprocessing.connection import Listener
2042 from array import array
2043
2044 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
2045 listener = Listener(address, authkey='secret password')
2046
2047 conn = listener.accept()
2048 print 'connection accepted from', listener.last_accepted
2049
2050 conn.send([2.25, None, 'junk', float])
2051
2052 conn.send_bytes('hello')
2053
2054 conn.send_bytes(array('i', [42, 1729]))
2055
2056 conn.close()
2057 listener.close()
2058
2059The following code connects to the server and receives some data from the
2060server::
2061
2062 from multiprocessing.connection import Client
2063 from array import array
2064
2065 address = ('localhost', 6000)
2066 conn = Client(address, authkey='secret password')
2067
2068 print conn.recv() # => [2.25, None, 'junk', float]
2069
2070 print conn.recv_bytes() # => 'hello'
2071
2072 arr = array('i', [0, 0, 0, 0, 0])
2073 print conn.recv_bytes_into(arr) # => 8
2074 print arr # => array('i', [42, 1729, 0, 0, 0])
2075
2076 conn.close()
2077
2078
2079.. _multiprocessing-address-formats:
2080
2081Address Formats
2082>>>>>>>>>>>>>>>
2083
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002084* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002085 *hostname* is a string and *port* is an integer.
2086
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002087* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002088 filesystem.
2089
2090* An ``'AF_PIPE'`` address is a string of the form
Georg Brandl6b28f392008-12-27 19:06:04 +00002091 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandlfc29f272009-01-02 20:25:14 +00002092 pipe on a remote computer called *ServerName* one should use an address of the
Georg Brandldd7e3132009-01-04 10:24:09 +00002093 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002094
2095Note that any string beginning with two backslashes is assumed by default to be
2096an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
2097
2098
2099.. _multiprocessing-auth-keys:
2100
2101Authentication keys
2102~~~~~~~~~~~~~~~~~~~
2103
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002104When one uses :meth:`Connection.recv <multiprocessing.Connection.recv>`, the
2105data received is automatically
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002106unpickled. Unfortunately unpickling data from an untrusted source is a security
2107risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
2108to provide digest authentication.
2109
2110An authentication key is a string which can be thought of as a password: once a
2111connection is established both ends will demand proof that the other knows the
2112authentication key. (Demonstrating that both ends are using the same key does
2113**not** involve sending the key over the connection.)
2114
2115If authentication is requested but do authentication key is specified then the
Benjamin Peterson73641d72008-08-20 14:07:59 +00002116return value of ``current_process().authkey`` is used (see
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002117:class:`~multiprocessing.Process`). This value will automatically inherited by
2118any :class:`~multiprocessing.Process` object that the current process creates.
2119This means that (by default) all processes of a multi-process program will share
2120a single authentication key which can be used when setting up connections
Andrew M. Kuchlinga178a692009-04-03 21:45:29 +00002121between themselves.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002122
2123Suitable authentication keys can also be generated by using :func:`os.urandom`.
2124
2125
2126Logging
2127~~~~~~~
2128
2129Some support for logging is available. Note, however, that the :mod:`logging`
2130package does not use process shared locks so it is possible (depending on the
2131handler type) for messages from different processes to get mixed up.
2132
2133.. currentmodule:: multiprocessing
2134.. function:: get_logger()
2135
2136 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
2137 will be created.
2138
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002139 When first created the logger has level :data:`logging.NOTSET` and no
2140 default handler. Messages sent to this logger will not by default propagate
2141 to the root logger.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002142
2143 Note that on Windows child processes will only inherit the level of the
2144 parent process's logger -- any other customization of the logger will not be
2145 inherited.
2146
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002147.. currentmodule:: multiprocessing
2148.. function:: log_to_stderr()
2149
2150 This function performs a call to :func:`get_logger` but in addition to
2151 returning the logger created by get_logger, it adds a handler which sends
2152 output to :data:`sys.stderr` using format
2153 ``'[%(levelname)s/%(processName)s] %(message)s'``.
2154
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002155Below is an example session with logging turned on::
2156
Georg Brandl19cc9442008-10-16 21:36:39 +00002157 >>> import multiprocessing, logging
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002158 >>> logger = multiprocessing.log_to_stderr()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002159 >>> logger.setLevel(logging.INFO)
2160 >>> logger.warning('doomed')
2161 [WARNING/MainProcess] doomed
Georg Brandl19cc9442008-10-16 21:36:39 +00002162 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002163 [INFO/SyncManager-...] child process calling self.run()
2164 [INFO/SyncManager-...] created temp directory /.../pymp-...
2165 [INFO/SyncManager-...] manager serving at '/.../listener-...'
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002166 >>> del m
2167 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002168 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002169
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002170In addition to having these two logging functions, the multiprocessing also
2171exposes two additional logging level attributes. These are :const:`SUBWARNING`
2172and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
2173normal level hierarchy.
2174
2175+----------------+----------------+
2176| Level | Numeric value |
2177+================+================+
2178| ``SUBWARNING`` | 25 |
2179+----------------+----------------+
2180| ``SUBDEBUG`` | 5 |
2181+----------------+----------------+
2182
2183For a full table of logging levels, see the :mod:`logging` module.
2184
2185These additional logging levels are used primarily for certain debug messages
2186within the multiprocessing module. Below is the same example as above, except
2187with :const:`SUBDEBUG` enabled::
2188
2189 >>> import multiprocessing, logging
2190 >>> logger = multiprocessing.log_to_stderr()
2191 >>> logger.setLevel(multiprocessing.SUBDEBUG)
2192 >>> logger.warning('doomed')
2193 [WARNING/MainProcess] doomed
2194 >>> m = multiprocessing.Manager()
R. David Murray636b23a2009-04-28 16:08:18 +00002195 [INFO/SyncManager-...] child process calling self.run()
2196 [INFO/SyncManager-...] created temp directory /.../pymp-...
2197 [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
Jesse Nollerb5a4b0a2009-01-25 03:36:13 +00002198 >>> del m
2199 [SUBDEBUG/MainProcess] finalizer calling ...
2200 [INFO/MainProcess] sending shutdown message to manager
R. David Murray636b23a2009-04-28 16:08:18 +00002201 [DEBUG/SyncManager-...] manager received shutdown message
2202 [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
2203 [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
2204 [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
2205 [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
2206 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002207
2208The :mod:`multiprocessing.dummy` module
2209~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2210
2211.. module:: multiprocessing.dummy
2212 :synopsis: Dumb wrapper around threading.
2213
2214:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002215no more than a wrapper around the :mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002216
2217
2218.. _multiprocessing-programming:
2219
2220Programming guidelines
2221----------------------
2222
2223There are certain guidelines and idioms which should be adhered to when using
2224:mod:`multiprocessing`.
2225
2226
2227All platforms
2228~~~~~~~~~~~~~
2229
2230Avoid shared state
2231
2232 As far as possible one should try to avoid shifting large amounts of data
2233 between processes.
2234
2235 It is probably best to stick to using queues or pipes for communication
2236 between processes rather than using the lower level synchronization
2237 primitives from the :mod:`threading` module.
2238
2239Picklability
2240
2241 Ensure that the arguments to the methods of proxies are picklable.
2242
2243Thread safety of proxies
2244
2245 Do not use a proxy object from more than one thread unless you protect it
2246 with a lock.
2247
2248 (There is never a problem with different processes using the *same* proxy.)
2249
2250Joining zombie processes
2251
2252 On Unix when a process finishes but has not been joined it becomes a zombie.
2253 There should never be very many because each time a new process starts (or
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002254 :func:`~multiprocessing.active_children` is called) all completed processes
2255 which have not yet been joined will be joined. Also calling a finished
2256 process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
2257 join the process. Even so it is probably good
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002258 practice to explicitly join all the processes that you start.
2259
2260Better to inherit than pickle/unpickle
2261
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002262 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002263 that child processes can use them. However, one should generally avoid
2264 sending shared objects to other processes using pipes or queues. Instead
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002265 you should arrange the program so that a process which needs access to a
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002266 shared resource created elsewhere can inherit it from an ancestor process.
2267
2268Avoid terminating processes
2269
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002270 Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
2271 method to stop a process is liable to
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002272 cause any shared resources (such as locks, semaphores, pipes and queues)
2273 currently being used by the process to become broken or unavailable to other
2274 processes.
2275
2276 Therefore it is probably best to only consider using
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002277 :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
2278 which never use any shared resources.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002279
2280Joining processes that use queues
2281
2282 Bear in mind that a process that has put items in a queue will wait before
2283 terminating until all the buffered items are fed by the "feeder" thread to
2284 the underlying pipe. (The child process can call the
Sandro Tosi8b48c662012-02-25 19:35:16 +01002285 :meth:`~multiprocessing.Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002286
2287 This means that whenever you use a queue you need to make sure that all
2288 items which have been put on the queue will eventually be removed before the
2289 process is joined. Otherwise you cannot be sure that processes which have
2290 put items on the queue will terminate. Remember also that non-daemonic
Zachary Ware06b74a72014-10-03 10:55:12 -05002291 processes will be joined automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002292
2293 An example which will deadlock is the following::
2294
2295 from multiprocessing import Process, Queue
2296
2297 def f(q):
2298 q.put('X' * 1000000)
2299
2300 if __name__ == '__main__':
2301 queue = Queue()
2302 p = Process(target=f, args=(queue,))
2303 p.start()
2304 p.join() # this deadlocks
2305 obj = queue.get()
2306
Zachary Ware06b74a72014-10-03 10:55:12 -05002307 A fix here would be to swap the last two lines (or simply remove the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002308 ``p.join()`` line).
2309
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00002310Explicitly pass resources to child processes
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002311
2312 On Unix a child process can make use of a shared resource created in a
2313 parent process using a global resource. However, it is better to pass the
2314 object as an argument to the constructor for the child process.
2315
2316 Apart from making the code (potentially) compatible with Windows this also
2317 ensures that as long as the child process is still alive the object will not
2318 be garbage collected in the parent process. This might be important if some
2319 resource is freed when the object is garbage collected in the parent
2320 process.
2321
2322 So for instance ::
2323
2324 from multiprocessing import Process, Lock
2325
2326 def f():
2327 ... do something using "lock" ...
2328
2329 if __name__ == '__main__':
2330 lock = Lock()
2331 for i in range(10):
2332 Process(target=f).start()
2333
2334 should be rewritten as ::
2335
2336 from multiprocessing import Process, Lock
2337
2338 def f(l):
2339 ... do something using "l" ...
2340
2341 if __name__ == '__main__':
2342 lock = Lock()
2343 for i in range(10):
2344 Process(target=f, args=(lock,)).start()
2345
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002346Beware of replacing :data:`sys.stdin` with a "file like object"
Jesse Noller1b90efb2009-06-30 17:11:52 +00002347
2348 :mod:`multiprocessing` originally unconditionally called::
2349
2350 os.close(sys.stdin.fileno())
2351
R. David Murray321afa82009-07-01 02:49:10 +00002352 in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
Jesse Noller1b90efb2009-06-30 17:11:52 +00002353 in issues with processes-in-processes. This has been changed to::
2354
2355 sys.stdin.close()
2356 sys.stdin = open(os.devnull)
2357
2358 Which solves the fundamental issue of processes colliding with each other
2359 resulting in a bad file descriptor error, but introduces a potential danger
2360 to applications which replace :func:`sys.stdin` with a "file-like object"
R. David Murray321afa82009-07-01 02:49:10 +00002361 with output buffering. This danger is that if multiple processes call
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002362 :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
Jesse Noller1b90efb2009-06-30 17:11:52 +00002363 data being flushed to the object multiple times, resulting in corruption.
2364
2365 If you write a file-like object and implement your own caching, you can
2366 make it fork-safe by storing the pid whenever you append to the cache,
2367 and discarding the cache when the pid changes. For example::
2368
2369 @property
2370 def cache(self):
2371 pid = os.getpid()
2372 if pid != self._pid:
2373 self._pid = pid
2374 self._cache = []
2375 return self._cache
2376
2377 For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002378
2379Windows
2380~~~~~~~
2381
2382Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2383
2384More picklability
2385
2386 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2387 means, in particular, that bound or unbound methods cannot be used directly
2388 as the ``target`` argument on Windows --- just define a function and use
2389 that instead.
2390
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002391 Also, if you subclass :class:`~multiprocessing.Process` then make sure that
2392 instances will be picklable when the :meth:`Process.start
2393 <multiprocessing.Process.start>` method is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002394
2395Global variables
2396
2397 Bear in mind that if code run in a child process tries to access a global
2398 variable, then the value it sees (if any) may not be the same as the value
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002399 in the parent process at the time that :meth:`Process.start
2400 <multiprocessing.Process.start>` was called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002401
2402 However, global variables which are just module level constants cause no
2403 problems.
2404
2405Safe importing of main module
2406
2407 Make sure that the main module can be safely imported by a new Python
2408 interpreter without causing unintended side effects (such a starting a new
2409 process).
2410
2411 For example, under Windows running the following module would fail with a
2412 :exc:`RuntimeError`::
2413
2414 from multiprocessing import Process
2415
2416 def foo():
2417 print 'hello'
2418
2419 p = Process(target=foo)
2420 p.start()
2421
2422 Instead one should protect the "entry point" of the program by using ``if
2423 __name__ == '__main__':`` as follows::
2424
2425 from multiprocessing import Process, freeze_support
2426
2427 def foo():
2428 print 'hello'
2429
2430 if __name__ == '__main__':
2431 freeze_support()
2432 p = Process(target=foo)
2433 p.start()
2434
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002435 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002436 normally instead of frozen.)
2437
2438 This allows the newly spawned Python interpreter to safely import the module
2439 and then run the module's ``foo()`` function.
2440
2441 Similar restrictions apply if a pool or manager is created in the main
2442 module.
2443
2444
2445.. _multiprocessing-examples:
2446
2447Examples
2448--------
2449
2450Demonstration of how to create and use customized managers and proxies:
2451
2452.. literalinclude:: ../includes/mp_newtype.py
2453
2454
Serhiy Storchakac8f26f52013-08-24 00:28:38 +03002455Using :class:`~multiprocessing.pool.Pool`:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002456
2457.. literalinclude:: ../includes/mp_pool.py
2458
2459
2460Synchronization types like locks, conditions and queues:
2461
2462.. literalinclude:: ../includes/mp_synchronize.py
2463
2464
Georg Brandl21946af2010-10-06 09:28:45 +00002465An example showing how to use queues to feed tasks to a collection of worker
Eli Bendersky4b76f8a2011-12-31 07:05:12 +02002466processes and collect the results:
Benjamin Peterson190d56e2008-06-11 02:40:25 +00002467
2468.. literalinclude:: ../includes/mp_workers.py
2469
2470
2471An example of how a pool of worker processes can each run a
2472:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2473socket.
2474
2475.. literalinclude:: ../includes/mp_webserver.py
2476
2477
2478Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2479
2480.. literalinclude:: ../includes/mp_benchmarks.py
2481