blob: d1b22dbd35564da829406cf49ec801f957884c85 [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001:mod:`multiprocessing` --- Process-based "threading" interface
2==============================================================
3
4.. module:: multiprocessing
5 :synopsis: Process-based "threading" interface.
6
Benjamin Petersone711caf2008-06-11 16:44:04 +00007
8Introduction
Georg Brandl49702152008-09-29 06:43:45 +00009------------
Benjamin Petersone711caf2008-06-11 16:44:04 +000010
Benjamin Peterson5289b2b2008-06-28 00:40:54 +000011:mod:`multiprocessing` is a package that supports spawning processes using an
12API similar to the :mod:`threading` module. The :mod:`multiprocessing` package
13offers both local and remote concurrency, effectively side-stepping the
14:term:`Global Interpreter Lock` by using subprocesses instead of threads. Due
15to this, the :mod:`multiprocessing` module allows the programmer to fully
16leverage multiple processors on a given machine. It runs on both Unix and
17Windows.
Benjamin Petersone711caf2008-06-11 16:44:04 +000018
Benjamin Petersone5384b02008-10-04 22:00:42 +000019.. warning::
20
21 Some of this package's functionality requires a functioning shared semaphore
Georg Brandl48310cd2009-01-03 21:18:54 +000022 implementation on the host operating system. Without one, the
23 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
24 import it will result in an :exc:`ImportError`. See
Benjamin Petersone5384b02008-10-04 22:00:42 +000025 :issue:`3770` for additional information.
Benjamin Petersone711caf2008-06-11 16:44:04 +000026
Jesse Noller45239682008-11-28 18:46:19 +000027.. note::
28
29 Functionality within this package requires that the ``__main__`` method be
30 importable by the children. This is covered in :ref:`multiprocessing-programming`
31 however it is worth pointing out here. This means that some examples, such
32 as the :class:`multiprocessing.Pool` examples will not work in the
33 interactive interpreter. For example::
34
35 >>> from multiprocessing import Pool
36 >>> p = Pool(5)
37 >>> def f(x):
Georg Brandla1c6a1c2009-01-03 21:26:05 +000038 ... return x*x
Georg Brandl48310cd2009-01-03 21:18:54 +000039 ...
Jesse Noller45239682008-11-28 18:46:19 +000040 >>> p.map(f, [1,2,3])
41 Process PoolWorker-1:
42 Process PoolWorker-2:
R. David Murray8e8099c2009-04-28 18:02:00 +000043 Process PoolWorker-3:
44 Traceback (most recent call last):
Jesse Noller45239682008-11-28 18:46:19 +000045 Traceback (most recent call last):
46 Traceback (most recent call last):
47 AttributeError: 'module' object has no attribute 'f'
48 AttributeError: 'module' object has no attribute 'f'
49 AttributeError: 'module' object has no attribute 'f'
50
R. David Murray8e8099c2009-04-28 18:02:00 +000051 (If you try this it will actually output three full tracebacks
52 interleaved in a semi-random fashion, and then you may have to
53 stop the master process somehow.)
54
Jesse Noller45239682008-11-28 18:46:19 +000055
Benjamin Petersone711caf2008-06-11 16:44:04 +000056The :class:`Process` class
57~~~~~~~~~~~~~~~~~~~~~~~~~~
58
59In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
Benjamin Peterson5289b2b2008-06-28 00:40:54 +000060object and then calling its :meth:`~Process.start` method. :class:`Process`
Benjamin Petersone711caf2008-06-11 16:44:04 +000061follows the API of :class:`threading.Thread`. A trivial example of a
62multiprocess program is ::
63
Jesse Noller45239682008-11-28 18:46:19 +000064 from multiprocessing import Process
Benjamin Petersone711caf2008-06-11 16:44:04 +000065
66 def f(name):
Georg Brandl49702152008-09-29 06:43:45 +000067 print('hello', name)
Benjamin Petersone711caf2008-06-11 16:44:04 +000068
Jesse Noller45239682008-11-28 18:46:19 +000069 if __name__ == '__main__':
70 p = Process(target=f, args=('bob',))
71 p.start()
72 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +000073
Jesse Noller45239682008-11-28 18:46:19 +000074To show the individual process IDs involved, here is an expanded example::
75
76 from multiprocessing import Process
77 import os
78
79 def info(title):
80 print title
81 print 'module name:', __name__
82 print 'parent process:', os.getppid()
83 print 'process id:', os.getpid()
Georg Brandl48310cd2009-01-03 21:18:54 +000084
Jesse Noller45239682008-11-28 18:46:19 +000085 def f(name):
86 info('function f')
87 print 'hello', name
Georg Brandl48310cd2009-01-03 21:18:54 +000088
Jesse Noller45239682008-11-28 18:46:19 +000089 if __name__ == '__main__':
90 info('main line')
91 p = Process(target=f, args=('bob',))
92 p.start()
93 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +000094
95For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is
96necessary, see :ref:`multiprocessing-programming`.
97
98
99
100Exchanging objects between processes
101~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
102
103:mod:`multiprocessing` supports two types of communication channel between
104processes:
105
106**Queues**
107
Benjamin Peterson257060a2008-06-28 01:42:41 +0000108 The :class:`Queue` class is a near clone of :class:`queue.Queue`. For
Benjamin Petersone711caf2008-06-11 16:44:04 +0000109 example::
110
111 from multiprocessing import Process, Queue
112
113 def f(q):
114 q.put([42, None, 'hello'])
115
Georg Brandl1f01deb2009-01-03 22:47:39 +0000116 if __name__ == '__main__':
117 q = Queue()
118 p = Process(target=f, args=(q,))
119 p.start()
120 print(q.get()) # prints "[42, None, 'hello']"
121 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000122
123 Queues are thread and process safe.
124
125**Pipes**
126
127 The :func:`Pipe` function returns a pair of connection objects connected by a
128 pipe which by default is duplex (two-way). For example::
129
130 from multiprocessing import Process, Pipe
131
132 def f(conn):
133 conn.send([42, None, 'hello'])
134 conn.close()
135
136 if __name__ == '__main__':
137 parent_conn, child_conn = Pipe()
138 p = Process(target=f, args=(child_conn,))
139 p.start()
Georg Brandl49702152008-09-29 06:43:45 +0000140 print(parent_conn.recv()) # prints "[42, None, 'hello']"
Benjamin Petersone711caf2008-06-11 16:44:04 +0000141 p.join()
142
143 The two connection objects returned by :func:`Pipe` represent the two ends of
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000144 the pipe. Each connection object has :meth:`~Connection.send` and
145 :meth:`~Connection.recv` methods (among others). Note that data in a pipe
146 may become corrupted if two processes (or threads) try to read from or write
147 to the *same* end of the pipe at the same time. Of course there is no risk
148 of corruption from processes using different ends of the pipe at the same
149 time.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000150
151
152Synchronization between processes
153~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
154
155:mod:`multiprocessing` contains equivalents of all the synchronization
156primitives from :mod:`threading`. For instance one can use a lock to ensure
157that only one process prints to standard output at a time::
158
159 from multiprocessing import Process, Lock
160
161 def f(l, i):
162 l.acquire()
Georg Brandl49702152008-09-29 06:43:45 +0000163 print('hello world', i)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000164 l.release()
165
166 if __name__ == '__main__':
167 lock = Lock()
168
169 for num in range(10):
170 Process(target=f, args=(lock, num)).start()
171
172Without using the lock output from the different processes is liable to get all
173mixed up.
174
175
176Sharing state between processes
177~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178
179As mentioned above, when doing concurrent programming it is usually best to
180avoid using shared state as far as possible. This is particularly true when
181using multiple processes.
182
183However, if you really do need to use some shared data then
184:mod:`multiprocessing` provides a couple of ways of doing so.
185
186**Shared memory**
187
188 Data can be stored in a shared memory map using :class:`Value` or
189 :class:`Array`. For example, the following code ::
190
191 from multiprocessing import Process, Value, Array
192
193 def f(n, a):
194 n.value = 3.1415927
195 for i in range(len(a)):
196 a[i] = -a[i]
197
198 if __name__ == '__main__':
199 num = Value('d', 0.0)
200 arr = Array('i', range(10))
201
202 p = Process(target=f, args=(num, arr))
203 p.start()
204 p.join()
205
Georg Brandl49702152008-09-29 06:43:45 +0000206 print(num.value)
207 print(arr[:])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000208
209 will print ::
210
211 3.1415927
212 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
213
214 The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
215 typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
Georg Brandl2ee470f2008-07-16 12:55:28 +0000216 double precision float and ``'i'`` indicates a signed integer. These shared
Benjamin Petersone711caf2008-06-11 16:44:04 +0000217 objects will be process and thread safe.
218
219 For more flexibility in using shared memory one can use the
220 :mod:`multiprocessing.sharedctypes` module which supports the creation of
221 arbitrary ctypes objects allocated from shared memory.
222
223**Server process**
224
225 A manager object returned by :func:`Manager` controls a server process which
Georg Brandl2ee470f2008-07-16 12:55:28 +0000226 holds Python objects and allows other processes to manipulate them using
Benjamin Petersone711caf2008-06-11 16:44:04 +0000227 proxies.
228
229 A manager returned by :func:`Manager` will support types :class:`list`,
230 :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`,
231 :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
232 :class:`Event`, :class:`Queue`, :class:`Value` and :class:`Array`. For
233 example, ::
234
235 from multiprocessing import Process, Manager
236
237 def f(d, l):
238 d[1] = '1'
239 d['2'] = 2
240 d[0.25] = None
241 l.reverse()
242
243 if __name__ == '__main__':
244 manager = Manager()
245
246 d = manager.dict()
247 l = manager.list(range(10))
248
249 p = Process(target=f, args=(d, l))
250 p.start()
251 p.join()
252
Georg Brandl49702152008-09-29 06:43:45 +0000253 print(d)
254 print(l)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000255
256 will print ::
257
258 {0.25: None, 1: '1', '2': 2}
259 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
260
261 Server process managers are more flexible than using shared memory objects
262 because they can be made to support arbitrary object types. Also, a single
263 manager can be shared by processes on different computers over a network.
264 They are, however, slower than using shared memory.
265
266
267Using a pool of workers
268~~~~~~~~~~~~~~~~~~~~~~~
269
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000270The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
Benjamin Petersone711caf2008-06-11 16:44:04 +0000271processes. It has methods which allows tasks to be offloaded to the worker
272processes in a few different ways.
273
274For example::
275
276 from multiprocessing import Pool
277
278 def f(x):
279 return x*x
280
281 if __name__ == '__main__':
Jesse Noller45239682008-11-28 18:46:19 +0000282 pool = Pool(processes=4) # start 4 worker processes
283 result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
284 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
285 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
Benjamin Petersone711caf2008-06-11 16:44:04 +0000286
287
288Reference
289---------
290
291The :mod:`multiprocessing` package mostly replicates the API of the
292:mod:`threading` module.
293
294
295:class:`Process` and exceptions
296~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
297
298.. class:: Process([group[, target[, name[, args[, kwargs]]]]])
299
300 Process objects represent activity that is run in a separate process. The
301 :class:`Process` class has equivalents of all the methods of
302 :class:`threading.Thread`.
303
304 The constructor should always be called with keyword arguments. *group*
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000305 should always be ``None``; it exists solely for compatibility with
Benjamin Petersona786b022008-08-25 21:05:21 +0000306 :class:`threading.Thread`. *target* is the callable object to be invoked by
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000307 the :meth:`run()` method. It defaults to ``None``, meaning nothing is
Benjamin Petersone711caf2008-06-11 16:44:04 +0000308 called. *name* is the process name. By default, a unique name is constructed
309 of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\
310 :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
311 is determined by the *generation* of the process. *args* is the argument
312 tuple for the target invocation. *kwargs* is a dictionary of keyword
313 arguments for the target invocation. By default, no arguments are passed to
314 *target*.
315
316 If a subclass overrides the constructor, it must make sure it invokes the
317 base class constructor (:meth:`Process.__init__`) before doing anything else
318 to the process.
319
320 .. method:: run()
321
322 Method representing the process's activity.
323
324 You may override this method in a subclass. The standard :meth:`run`
325 method invokes the callable object passed to the object's constructor as
326 the target argument, if any, with sequential and keyword arguments taken
327 from the *args* and *kwargs* arguments, respectively.
328
329 .. method:: start()
330
331 Start the process's activity.
332
333 This must be called at most once per process object. It arranges for the
334 object's :meth:`run` method to be invoked in a separate process.
335
336 .. method:: join([timeout])
337
338 Block the calling thread until the process whose :meth:`join` method is
339 called terminates or until the optional timeout occurs.
340
341 If *timeout* is ``None`` then there is no timeout.
342
343 A process can be joined many times.
344
345 A process cannot join itself because this would cause a deadlock. It is
346 an error to attempt to join a process before it has been started.
347
Benjamin Petersona786b022008-08-25 21:05:21 +0000348 .. attribute:: name
Benjamin Petersone711caf2008-06-11 16:44:04 +0000349
Benjamin Petersona786b022008-08-25 21:05:21 +0000350 The process's name.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000351
352 The name is a string used for identification purposes only. It has no
353 semantics. Multiple processes may be given the same name. The initial
354 name is set by the constructor.
355
Jesse Noller45239682008-11-28 18:46:19 +0000356 .. method:: is_alive
Benjamin Petersone711caf2008-06-11 16:44:04 +0000357
358 Return whether the process is alive.
359
360 Roughly, a process object is alive from the moment the :meth:`start`
361 method returns until the child process terminates.
362
Benjamin Petersona786b022008-08-25 21:05:21 +0000363 .. attribute:: daemon
Benjamin Petersone711caf2008-06-11 16:44:04 +0000364
Benjamin Petersonda10d3b2009-01-01 00:23:30 +0000365 The process's daemon flag, a Boolean value. This must be set before
Benjamin Petersona786b022008-08-25 21:05:21 +0000366 :meth:`start` is called.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000367
368 The initial value is inherited from the creating process.
369
370 When a process exits, it attempts to terminate all of its daemonic child
371 processes.
372
373 Note that a daemonic process is not allowed to create child processes.
374 Otherwise a daemonic process would leave its children orphaned if it gets
375 terminated when its parent process exits.
376
Benjamin Petersona786b022008-08-25 21:05:21 +0000377 In addition to the :class:`Threading.Thread` API, :class:`Process` objects
378 also support the following attributes and methods:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000379
Benjamin Petersona786b022008-08-25 21:05:21 +0000380 .. attribute:: pid
Benjamin Petersone711caf2008-06-11 16:44:04 +0000381
382 Return the process ID. Before the process is spawned, this will be
383 ``None``.
384
Benjamin Petersona786b022008-08-25 21:05:21 +0000385 .. attribute:: exitcode
Benjamin Petersone711caf2008-06-11 16:44:04 +0000386
Benjamin Petersona786b022008-08-25 21:05:21 +0000387 The child's exit code. This will be ``None`` if the process has not yet
388 terminated. A negative value *-N* indicates that the child was terminated
389 by signal *N*.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000390
Benjamin Petersona786b022008-08-25 21:05:21 +0000391 .. attribute:: authkey
Benjamin Petersone711caf2008-06-11 16:44:04 +0000392
Benjamin Petersona786b022008-08-25 21:05:21 +0000393 The process's authentication key (a byte string).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000394
395 When :mod:`multiprocessing` is initialized the main process is assigned a
396 random string using :func:`os.random`.
397
398 When a :class:`Process` object is created, it will inherit the
Benjamin Petersona786b022008-08-25 21:05:21 +0000399 authentication key of its parent process, although this may be changed by
400 setting :attr:`authkey` to another byte string.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000401
402 See :ref:`multiprocessing-auth-keys`.
403
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000404 .. method:: terminate()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000405
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000406 Terminate the process. On Unix this is done using the ``SIGTERM`` signal;
407 on Windows :cfunc:`TerminateProcess` is used. Note that exit handlers and
408 finally clauses, etc., will not be executed.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000409
410 Note that descendant processes of the process will *not* be terminated --
411 they will simply become orphaned.
412
413 .. warning::
414
415 If this method is used when the associated process is using a pipe or
416 queue then the pipe or queue is liable to become corrupted and may
417 become unusable by other process. Similarly, if the process has
418 acquired a lock or semaphore etc. then terminating it is liable to
419 cause other processes to deadlock.
420
421 Note that the :meth:`start`, :meth:`join`, :meth:`is_alive` and
Benjamin Petersona786b022008-08-25 21:05:21 +0000422 :attr:`exit_code` methods should only be called by the process that created
423 the process object.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000424
R. David Murray8e8099c2009-04-28 18:02:00 +0000425 Example usage of some of the methods of :class:`Process`:
426
427 .. doctest::
Benjamin Petersone711caf2008-06-11 16:44:04 +0000428
Benjamin Peterson206e3072008-10-19 14:07:49 +0000429 >>> import multiprocessing, time, signal
430 >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
Georg Brandl49702152008-09-29 06:43:45 +0000431 >>> print(p, p.is_alive())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000432 <Process(Process-1, initial)> False
433 >>> p.start()
Georg Brandl49702152008-09-29 06:43:45 +0000434 >>> print(p, p.is_alive())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000435 <Process(Process-1, started)> True
436 >>> p.terminate()
R. David Murray8e8099c2009-04-28 18:02:00 +0000437 >>> time.sleep(0.1)
Georg Brandl49702152008-09-29 06:43:45 +0000438 >>> print(p, p.is_alive())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000439 <Process(Process-1, stopped[SIGTERM])> False
Benjamin Petersona786b022008-08-25 21:05:21 +0000440 >>> p.exitcode == -signal.SIGTERM
Benjamin Petersone711caf2008-06-11 16:44:04 +0000441 True
442
443
444.. exception:: BufferTooShort
445
446 Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
447 buffer object is too small for the message read.
448
449 If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
450 the message as a byte string.
451
452
453Pipes and Queues
454~~~~~~~~~~~~~~~~
455
456When using multiple processes, one generally uses message passing for
457communication between processes and avoids having to use any synchronization
458primitives like locks.
459
460For passing messages one can use :func:`Pipe` (for a connection between two
461processes) or a queue (which allows multiple producers and consumers).
462
463The :class:`Queue` and :class:`JoinableQueue` types are multi-producer,
Benjamin Peterson257060a2008-06-28 01:42:41 +0000464multi-consumer FIFO queues modelled on the :class:`queue.Queue` class in the
Benjamin Petersone711caf2008-06-11 16:44:04 +0000465standard library. They differ in that :class:`Queue` lacks the
Benjamin Peterson257060a2008-06-28 01:42:41 +0000466:meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join` methods introduced
467into Python 2.5's :class:`queue.Queue` class.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000468
469If you use :class:`JoinableQueue` then you **must** call
470:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
471semaphore used to count the number of unfinished tasks may eventually overflow
472raising an exception.
473
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000474Note that one can also create a shared queue by using a manager object -- see
475:ref:`multiprocessing-managers`.
476
Benjamin Petersone711caf2008-06-11 16:44:04 +0000477.. note::
478
Benjamin Peterson257060a2008-06-28 01:42:41 +0000479 :mod:`multiprocessing` uses the usual :exc:`queue.Empty` and
480 :exc:`queue.Full` exceptions to signal a timeout. They are not available in
Benjamin Petersone711caf2008-06-11 16:44:04 +0000481 the :mod:`multiprocessing` namespace so you need to import them from
Benjamin Peterson257060a2008-06-28 01:42:41 +0000482 :mod:`queue`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000483
484
485.. warning::
486
487 If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
488 while it is trying to use a :class:`Queue`, then the data in the queue is
489 likely to become corrupted. This may cause any other processes to get an
490 exception when it tries to use the queue later on.
491
492.. warning::
493
494 As mentioned above, if a child process has put items on a queue (and it has
495 not used :meth:`JoinableQueue.cancel_join_thread`), then that process will
496 not terminate until all buffered items have been flushed to the pipe.
497
498 This means that if you try joining that process you may get a deadlock unless
499 you are sure that all items which have been put on the queue have been
500 consumed. Similarly, if the child process is non-daemonic then the parent
Georg Brandl2ee470f2008-07-16 12:55:28 +0000501 process may hang on exit when it tries to join all its non-daemonic children.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000502
503 Note that a queue created using a manager does not have this issue. See
504 :ref:`multiprocessing-programming`.
505
Benjamin Petersone711caf2008-06-11 16:44:04 +0000506For an example of the usage of queues for interprocess communication see
507:ref:`multiprocessing-examples`.
508
509
510.. function:: Pipe([duplex])
511
512 Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing
513 the ends of a pipe.
514
515 If *duplex* is ``True`` (the default) then the pipe is bidirectional. If
516 *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
517 used for receiving messages and ``conn2`` can only be used for sending
518 messages.
519
520
521.. class:: Queue([maxsize])
522
523 Returns a process shared queue implemented using a pipe and a few
524 locks/semaphores. When a process first puts an item on the queue a feeder
525 thread is started which transfers objects from a buffer into the pipe.
526
Benjamin Peterson257060a2008-06-28 01:42:41 +0000527 The usual :exc:`queue.Empty` and :exc:`queue.Full` exceptions from the
Benjamin Petersone711caf2008-06-11 16:44:04 +0000528 standard library's :mod:`Queue` module are raised to signal timeouts.
529
Benjamin Peterson257060a2008-06-28 01:42:41 +0000530 :class:`Queue` implements all the methods of :class:`queue.Queue` except for
531 :meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000532
533 .. method:: qsize()
534
535 Return the approximate size of the queue. Because of
536 multithreading/multiprocessing semantics, this number is not reliable.
537
538 Note that this may raise :exc:`NotImplementedError` on Unix platforms like
Georg Brandlc575c902008-09-13 17:46:05 +0000539 Mac OS X where ``sem_getvalue()`` is not implemented.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000540
541 .. method:: empty()
542
543 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
544 multithreading/multiprocessing semantics, this is not reliable.
545
546 .. method:: full()
547
548 Return ``True`` if the queue is full, ``False`` otherwise. Because of
549 multithreading/multiprocessing semantics, this is not reliable.
550
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000551 .. method:: put(item[, block[, timeout]])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000552
Georg Brandl48310cd2009-01-03 21:18:54 +0000553 Put item into the queue. If the optional argument *block* is ``True``
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000554 (the default) and *timeout* is ``None`` (the default), block if necessary until
Benjamin Petersone711caf2008-06-11 16:44:04 +0000555 a free slot is available. If *timeout* is a positive number, it blocks at
Benjamin Peterson257060a2008-06-28 01:42:41 +0000556 most *timeout* seconds and raises the :exc:`queue.Full` exception if no
Benjamin Petersone711caf2008-06-11 16:44:04 +0000557 free slot was available within that time. Otherwise (*block* is
558 ``False``), put an item on the queue if a free slot is immediately
Benjamin Peterson257060a2008-06-28 01:42:41 +0000559 available, else raise the :exc:`queue.Full` exception (*timeout* is
Benjamin Petersone711caf2008-06-11 16:44:04 +0000560 ignored in that case).
561
562 .. method:: put_nowait(item)
563
564 Equivalent to ``put(item, False)``.
565
566 .. method:: get([block[, timeout]])
567
568 Remove and return an item from the queue. If optional args *block* is
569 ``True`` (the default) and *timeout* is ``None`` (the default), block if
570 necessary until an item is available. If *timeout* is a positive number,
Benjamin Peterson257060a2008-06-28 01:42:41 +0000571 it blocks at most *timeout* seconds and raises the :exc:`queue.Empty`
Benjamin Petersone711caf2008-06-11 16:44:04 +0000572 exception if no item was available within that time. Otherwise (block is
573 ``False``), return an item if one is immediately available, else raise the
Benjamin Peterson257060a2008-06-28 01:42:41 +0000574 :exc:`queue.Empty` exception (*timeout* is ignored in that case).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000575
576 .. method:: get_nowait()
577 get_no_wait()
578
579 Equivalent to ``get(False)``.
580
581 :class:`multiprocessing.Queue` has a few additional methods not found in
Georg Brandl2ee470f2008-07-16 12:55:28 +0000582 :class:`queue.Queue`. These methods are usually unnecessary for most
583 code:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000584
585 .. method:: close()
586
587 Indicate that no more data will be put on this queue by the current
588 process. The background thread will quit once it has flushed all buffered
589 data to the pipe. This is called automatically when the queue is garbage
590 collected.
591
592 .. method:: join_thread()
593
594 Join the background thread. This can only be used after :meth:`close` has
595 been called. It blocks until the background thread exits, ensuring that
596 all data in the buffer has been flushed to the pipe.
597
598 By default if a process is not the creator of the queue then on exit it
599 will attempt to join the queue's background thread. The process can call
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000600 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000601
602 .. method:: cancel_join_thread()
603
604 Prevent :meth:`join_thread` from blocking. In particular, this prevents
605 the background thread from being joined automatically when the process
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000606 exits -- see :meth:`join_thread`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000607
608
609.. class:: JoinableQueue([maxsize])
610
611 :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which
612 additionally has :meth:`task_done` and :meth:`join` methods.
613
614 .. method:: task_done()
615
616 Indicate that a formerly enqueued task is complete. Used by queue consumer
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000617 threads. For each :meth:`~Queue.get` used to fetch a task, a subsequent
618 call to :meth:`task_done` tells the queue that the processing on the task
619 is complete.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000620
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000621 If a :meth:`~Queue.join` is currently blocking, it will resume when all
622 items have been processed (meaning that a :meth:`task_done` call was
623 received for every item that had been :meth:`~Queue.put` into the queue).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000624
625 Raises a :exc:`ValueError` if called more times than there were items
626 placed in the queue.
627
628
629 .. method:: join()
630
631 Block until all items in the queue have been gotten and processed.
632
633 The count of unfinished tasks goes up whenever an item is added to the
634 queue. The count goes down whenever a consumer thread calls
635 :meth:`task_done` to indicate that the item was retrieved and all work on
636 it is complete. When the count of unfinished tasks drops to zero,
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000637 :meth:`~Queue.join` unblocks.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000638
639
640Miscellaneous
641~~~~~~~~~~~~~
642
643.. function:: active_children()
644
645 Return list of all live children of the current process.
646
647 Calling this has the side affect of "joining" any processes which have
648 already finished.
649
650.. function:: cpu_count()
651
652 Return the number of CPUs in the system. May raise
653 :exc:`NotImplementedError`.
654
655.. function:: current_process()
656
657 Return the :class:`Process` object corresponding to the current process.
658
659 An analogue of :func:`threading.current_thread`.
660
661.. function:: freeze_support()
662
663 Add support for when a program which uses :mod:`multiprocessing` has been
664 frozen to produce a Windows executable. (Has been tested with **py2exe**,
665 **PyInstaller** and **cx_Freeze**.)
666
667 One needs to call this function straight after the ``if __name__ ==
668 '__main__'`` line of the main module. For example::
669
670 from multiprocessing import Process, freeze_support
671
672 def f():
Georg Brandl49702152008-09-29 06:43:45 +0000673 print('hello world!')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000674
675 if __name__ == '__main__':
676 freeze_support()
677 Process(target=f).start()
678
R. David Murray8e8099c2009-04-28 18:02:00 +0000679 If the ``freeze_support()`` line is omitted then trying to run the frozen
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000680 executable will raise :exc:`RuntimeError`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000681
682 If the module is being run normally by the Python interpreter then
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000683 :func:`freeze_support` has no effect.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000684
685.. function:: set_executable()
686
687 Sets the path of the python interpreter to use when starting a child process.
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000688 (By default :data:`sys.executable` is used). Embedders will probably need to
689 do some thing like ::
Benjamin Petersone711caf2008-06-11 16:44:04 +0000690
691 setExecutable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
692
R. David Murray8e8099c2009-04-28 18:02:00 +0000693 before they can create child processes. (Windows only)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000694
695
696.. note::
697
698 :mod:`multiprocessing` contains no analogues of
699 :func:`threading.active_count`, :func:`threading.enumerate`,
700 :func:`threading.settrace`, :func:`threading.setprofile`,
701 :class:`threading.Timer`, or :class:`threading.local`.
702
703
704Connection Objects
705~~~~~~~~~~~~~~~~~~
706
707Connection objects allow the sending and receiving of picklable objects or
708strings. They can be thought of as message oriented connected sockets.
709
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000710Connection objects usually created using :func:`Pipe` -- see also
Benjamin Petersone711caf2008-06-11 16:44:04 +0000711:ref:`multiprocessing-listeners-clients`.
712
713.. class:: Connection
714
715 .. method:: send(obj)
716
717 Send an object to the other end of the connection which should be read
718 using :meth:`recv`.
719
Benjamin Peterson965ce872009-04-05 21:24:58 +0000720 The object must be picklable. Very large pickles (approximately 32 MB+,
721 though it depends on the OS) may raise a ValueError exception.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000722
723 .. method:: recv()
724
725 Return an object sent from the other end of the connection using
726 :meth:`send`. Raises :exc:`EOFError` if there is nothing left to receive
727 and the other end was closed.
728
729 .. method:: fileno()
730
731 Returns the file descriptor or handle used by the connection.
732
733 .. method:: close()
734
735 Close the connection.
736
737 This is called automatically when the connection is garbage collected.
738
739 .. method:: poll([timeout])
740
741 Return whether there is any data available to be read.
742
743 If *timeout* is not specified then it will return immediately. If
744 *timeout* is a number then this specifies the maximum time in seconds to
745 block. If *timeout* is ``None`` then an infinite timeout is used.
746
747 .. method:: send_bytes(buffer[, offset[, size]])
748
749 Send byte data from an object supporting the buffer interface as a
750 complete message.
751
752 If *offset* is given then data is read from that position in *buffer*. If
Benjamin Peterson965ce872009-04-05 21:24:58 +0000753 *size* is given then that many bytes will be read from buffer. Very large
754 buffers (approximately 32 MB+, though it depends on the OS) may raise a
755 ValueError exception
Benjamin Petersone711caf2008-06-11 16:44:04 +0000756
757 .. method:: recv_bytes([maxlength])
758
759 Return a complete message of byte data sent from the other end of the
760 connection as a string. Raises :exc:`EOFError` if there is nothing left
761 to receive and the other end has closed.
762
763 If *maxlength* is specified and the message is longer than *maxlength*
764 then :exc:`IOError` is raised and the connection will no longer be
765 readable.
766
767 .. method:: recv_bytes_into(buffer[, offset])
768
769 Read into *buffer* a complete message of byte data sent from the other end
770 of the connection and return the number of bytes in the message. Raises
771 :exc:`EOFError` if there is nothing left to receive and the other end was
772 closed.
773
774 *buffer* must be an object satisfying the writable buffer interface. If
775 *offset* is given then the message will be written into the buffer from
R. David Murray8e8099c2009-04-28 18:02:00 +0000776 that position. Offset must be a non-negative integer less than the
777 length of *buffer* (in bytes).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000778
779 If the buffer is too short then a :exc:`BufferTooShort` exception is
780 raised and the complete message is available as ``e.args[0]`` where ``e``
781 is the exception instance.
782
783
784For example:
785
R. David Murray8e8099c2009-04-28 18:02:00 +0000786.. doctest::
787
Benjamin Petersone711caf2008-06-11 16:44:04 +0000788 >>> from multiprocessing import Pipe
789 >>> a, b = Pipe()
790 >>> a.send([1, 'hello', None])
791 >>> b.recv()
792 [1, 'hello', None]
793 >>> b.send_bytes('thank you')
794 >>> a.recv_bytes()
795 'thank you'
796 >>> import array
797 >>> arr1 = array.array('i', range(5))
798 >>> arr2 = array.array('i', [0] * 10)
799 >>> a.send_bytes(arr1)
800 >>> count = b.recv_bytes_into(arr2)
801 >>> assert count == len(arr1) * arr1.itemsize
802 >>> arr2
803 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
804
805
806.. warning::
807
808 The :meth:`Connection.recv` method automatically unpickles the data it
809 receives, which can be a security risk unless you can trust the process
810 which sent the message.
811
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000812 Therefore, unless the connection object was produced using :func:`Pipe` you
813 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
814 methods after performing some sort of authentication. See
815 :ref:`multiprocessing-auth-keys`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000816
817.. warning::
818
819 If a process is killed while it is trying to read or write to a pipe then
820 the data in the pipe is likely to become corrupted, because it may become
821 impossible to be sure where the message boundaries lie.
822
823
824Synchronization primitives
825~~~~~~~~~~~~~~~~~~~~~~~~~~
826
827Generally synchronization primitives are not as necessary in a multiprocess
Georg Brandl2ee470f2008-07-16 12:55:28 +0000828program as they are in a multithreaded program. See the documentation for
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000829:mod:`threading` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000830
831Note that one can also create synchronization primitives by using a manager
832object -- see :ref:`multiprocessing-managers`.
833
834.. class:: BoundedSemaphore([value])
835
836 A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`.
837
Georg Brandlc575c902008-09-13 17:46:05 +0000838 (On Mac OS X this is indistinguishable from :class:`Semaphore` because
Benjamin Petersone711caf2008-06-11 16:44:04 +0000839 ``sem_getvalue()`` is not implemented on that platform).
840
841.. class:: Condition([lock])
842
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000843 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000844
845 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
846 object from :mod:`multiprocessing`.
847
848.. class:: Event()
849
850 A clone of :class:`threading.Event`.
Benjamin Peterson965ce872009-04-05 21:24:58 +0000851 This method returns the state of the internal semaphore on exit, so it
852 will always return ``True`` except if a timeout is given and the operation
853 times out.
854
Raymond Hettinger35a88362009-04-09 00:08:24 +0000855 .. versionchanged:: 3.1
Benjamin Peterson965ce872009-04-05 21:24:58 +0000856 Previously, the method always returned ``None``.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000857
858.. class:: Lock()
859
860 A non-recursive lock object: a clone of :class:`threading.Lock`.
861
862.. class:: RLock()
863
864 A recursive lock object: a clone of :class:`threading.RLock`.
865
866.. class:: Semaphore([value])
867
868 A bounded semaphore object: a clone of :class:`threading.Semaphore`.
869
870.. note::
871
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000872 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Petersone711caf2008-06-11 16:44:04 +0000873 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
874 by the equivalents in :mod:`threading`. The signature is
875 ``acquire(block=True, timeout=None)`` with keyword parameters being
876 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
877 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
878 ignored.
Georg Brandl48310cd2009-01-03 21:18:54 +0000879
R. David Murray8e8099c2009-04-28 18:02:00 +0000880.. note::
881 On OS/X ``sem_timedwait`` is unsupported, so timeout arguments for the
882 aforementioned :meth:`acquire` methods will be ignored on OS/X.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000883
884.. note::
885
886 If the SIGINT signal generated by Ctrl-C arrives while the main thread is
887 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
888 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
889 or :meth:`Condition.wait` then the call will be immediately interrupted and
890 :exc:`KeyboardInterrupt` will be raised.
891
892 This differs from the behaviour of :mod:`threading` where SIGINT will be
893 ignored while the equivalent blocking calls are in progress.
894
895
896Shared :mod:`ctypes` Objects
897~~~~~~~~~~~~~~~~~~~~~~~~~~~~
898
899It is possible to create shared objects using shared memory which can be
900inherited by child processes.
901
Jesse Nollerb0516a62009-01-18 03:11:38 +0000902.. function:: Value(typecode_or_type, *args[, lock])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000903
904 Return a :mod:`ctypes` object allocated from shared memory. By default the
905 return value is actually a synchronized wrapper for the object.
906
907 *typecode_or_type* determines the type of the returned object: it is either a
908 ctypes type or a one character typecode of the kind used by the :mod:`array`
909 module. *\*args* is passed on to the constructor for the type.
910
911 If *lock* is ``True`` (the default) then a new lock object is created to
912 synchronize access to the value. If *lock* is a :class:`Lock` or
913 :class:`RLock` object then that will be used to synchronize access to the
914 value. If *lock* is ``False`` then access to the returned object will not be
915 automatically protected by a lock, so it will not necessarily be
916 "process-safe".
917
918 Note that *lock* is a keyword-only argument.
919
920.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
921
922 Return a ctypes array allocated from shared memory. By default the return
923 value is actually a synchronized wrapper for the array.
924
925 *typecode_or_type* determines the type of the elements of the returned array:
926 it is either a ctypes type or a one character typecode of the kind used by
927 the :mod:`array` module. If *size_or_initializer* is an integer, then it
928 determines the length of the array, and the array will be initially zeroed.
929 Otherwise, *size_or_initializer* is a sequence which is used to initialize
930 the array and whose length determines the length of the array.
931
932 If *lock* is ``True`` (the default) then a new lock object is created to
933 synchronize access to the value. If *lock* is a :class:`Lock` or
934 :class:`RLock` object then that will be used to synchronize access to the
935 value. If *lock* is ``False`` then access to the returned object will not be
936 automatically protected by a lock, so it will not necessarily be
937 "process-safe".
938
939 Note that *lock* is a keyword only argument.
940
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000941 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
Benjamin Petersone711caf2008-06-11 16:44:04 +0000942 attributes which allow one to use it to store and retrieve strings.
943
944
945The :mod:`multiprocessing.sharedctypes` module
946>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
947
948.. module:: multiprocessing.sharedctypes
949 :synopsis: Allocate ctypes objects from shared memory.
950
951The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
952:mod:`ctypes` objects from shared memory which can be inherited by child
953processes.
954
955.. note::
956
Georg Brandl2ee470f2008-07-16 12:55:28 +0000957 Although it is possible to store a pointer in shared memory remember that
958 this will refer to a location in the address space of a specific process.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000959 However, the pointer is quite likely to be invalid in the context of a second
960 process and trying to dereference the pointer from the second process may
961 cause a crash.
962
963.. function:: RawArray(typecode_or_type, size_or_initializer)
964
965 Return a ctypes array allocated from shared memory.
966
967 *typecode_or_type* determines the type of the elements of the returned array:
968 it is either a ctypes type or a one character typecode of the kind used by
969 the :mod:`array` module. If *size_or_initializer* is an integer then it
970 determines the length of the array, and the array will be initially zeroed.
971 Otherwise *size_or_initializer* is a sequence which is used to initialize the
972 array and whose length determines the length of the array.
973
974 Note that setting and getting an element is potentially non-atomic -- use
975 :func:`Array` instead to make sure that access is automatically synchronized
976 using a lock.
977
978.. function:: RawValue(typecode_or_type, *args)
979
980 Return a ctypes object allocated from shared memory.
981
982 *typecode_or_type* determines the type of the returned object: it is either a
983 ctypes type or a one character typecode of the kind used by the :mod:`array`
Jesse Nollerb0516a62009-01-18 03:11:38 +0000984 module. *\*args* is passed on to the constructor for the type.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000985
986 Note that setting and getting the value is potentially non-atomic -- use
987 :func:`Value` instead to make sure that access is automatically synchronized
988 using a lock.
989
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000990 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
Benjamin Petersone711caf2008-06-11 16:44:04 +0000991 attributes which allow one to use it to store and retrieve strings -- see
992 documentation for :mod:`ctypes`.
993
Jesse Nollerb0516a62009-01-18 03:11:38 +0000994.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000995
996 The same as :func:`RawArray` except that depending on the value of *lock* a
997 process-safe synchronization wrapper may be returned instead of a raw ctypes
998 array.
999
1000 If *lock* is ``True`` (the default) then a new lock object is created to
1001 synchronize access to the value. If *lock* is a :class:`Lock` or
1002 :class:`RLock` object then that will be used to synchronize access to the
1003 value. If *lock* is ``False`` then access to the returned object will not be
1004 automatically protected by a lock, so it will not necessarily be
1005 "process-safe".
1006
1007 Note that *lock* is a keyword-only argument.
1008
1009.. function:: Value(typecode_or_type, *args[, lock])
1010
1011 The same as :func:`RawValue` except that depending on the value of *lock* a
1012 process-safe synchronization wrapper may be returned instead of a raw ctypes
1013 object.
1014
1015 If *lock* is ``True`` (the default) then a new lock object is created to
1016 synchronize access to the value. If *lock* is a :class:`Lock` or
1017 :class:`RLock` object then that will be used to synchronize access to the
1018 value. If *lock* is ``False`` then access to the returned object will not be
1019 automatically protected by a lock, so it will not necessarily be
1020 "process-safe".
1021
1022 Note that *lock* is a keyword-only argument.
1023
1024.. function:: copy(obj)
1025
1026 Return a ctypes object allocated from shared memory which is a copy of the
1027 ctypes object *obj*.
1028
1029.. function:: synchronized(obj[, lock])
1030
1031 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1032 synchronize access. If *lock* is ``None`` (the default) then a
1033 :class:`multiprocessing.RLock` object is created automatically.
1034
1035 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001036 object it wraps: :meth:`get_obj` returns the wrapped object and
1037 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001038
1039 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001040 than accessing the raw ctypes object.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001041
1042
1043The table below compares the syntax for creating shared ctypes objects from
1044shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1045subclass of :class:`ctypes.Structure`.)
1046
1047==================== ========================== ===========================
1048ctypes sharedctypes using type sharedctypes using typecode
1049==================== ========================== ===========================
1050c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1051MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1052(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1053(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1054==================== ========================== ===========================
1055
1056
1057Below is an example where a number of ctypes objects are modified by a child
1058process::
1059
1060 from multiprocessing import Process, Lock
1061 from multiprocessing.sharedctypes import Value, Array
1062 from ctypes import Structure, c_double
1063
1064 class Point(Structure):
1065 _fields_ = [('x', c_double), ('y', c_double)]
1066
1067 def modify(n, x, s, A):
1068 n.value **= 2
1069 x.value **= 2
1070 s.value = s.value.upper()
1071 for a in A:
1072 a.x **= 2
1073 a.y **= 2
1074
1075 if __name__ == '__main__':
1076 lock = Lock()
1077
1078 n = Value('i', 7)
R. David Murray8e8099c2009-04-28 18:02:00 +00001079 x = Value(c_double, 1.0/3.0, lock=False)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001080 s = Array('c', 'hello world', lock=lock)
1081 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1082
1083 p = Process(target=modify, args=(n, x, s, A))
1084 p.start()
1085 p.join()
1086
Georg Brandl49702152008-09-29 06:43:45 +00001087 print(n.value)
1088 print(x.value)
1089 print(s.value)
1090 print([(a.x, a.y) for a in A])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001091
1092
Georg Brandl49702152008-09-29 06:43:45 +00001093.. highlight:: none
Benjamin Petersone711caf2008-06-11 16:44:04 +00001094
1095The results printed are ::
1096
1097 49
1098 0.1111111111111111
1099 HELLO WORLD
1100 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1101
Georg Brandl49702152008-09-29 06:43:45 +00001102.. highlight:: python
Benjamin Petersone711caf2008-06-11 16:44:04 +00001103
1104
1105.. _multiprocessing-managers:
1106
1107Managers
1108~~~~~~~~
1109
1110Managers provide a way to create data which can be shared between different
1111processes. A manager object controls a server process which manages *shared
1112objects*. Other processes can access the shared objects by using proxies.
1113
1114.. function:: multiprocessing.Manager()
1115
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001116 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1117 can be used for sharing objects between processes. The returned manager
1118 object corresponds to a spawned child process and has methods which will
1119 create shared objects and return corresponding proxies.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001120
1121.. module:: multiprocessing.managers
1122 :synopsis: Share data between process with shared objects.
1123
1124Manager processes will be shutdown as soon as they are garbage collected or
1125their parent process exits. The manager classes are defined in the
1126:mod:`multiprocessing.managers` module:
1127
1128.. class:: BaseManager([address[, authkey]])
1129
1130 Create a BaseManager object.
1131
1132 Once created one should call :meth:`start` or :meth:`serve_forever` to ensure
1133 that the manager object refers to a started manager process.
1134
1135 *address* is the address on which the manager process listens for new
1136 connections. If *address* is ``None`` then an arbitrary one is chosen.
1137
1138 *authkey* is the authentication key which will be used to check the validity
1139 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Petersona786b022008-08-25 21:05:21 +00001140 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Petersone711caf2008-06-11 16:44:04 +00001141 must be a string.
1142
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001143 .. method:: start([initializer[, initargs]])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001144
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001145 Start a subprocess to start the manager. If *initializer* is not ``None``
1146 then the subprocess will call ``initializer(*initargs)`` when it starts.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001147
Georg Brandl2ee470f2008-07-16 12:55:28 +00001148 .. method:: serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001149
1150 Run the server in the current process.
1151
1152 .. method:: from_address(address, authkey)
1153
1154 A class method which creates a manager object referring to a pre-existing
1155 server process which is using the given address and authentication key.
1156
Jesse Noller45239682008-11-28 18:46:19 +00001157 .. method:: get_server()
Georg Brandl48310cd2009-01-03 21:18:54 +00001158
Jesse Noller45239682008-11-28 18:46:19 +00001159 Returns a :class:`Server` object which represents the actual server under
Georg Brandl48310cd2009-01-03 21:18:54 +00001160 the control of the Manager. The :class:`Server` object supports the
R. David Murray8e8099c2009-04-28 18:02:00 +00001161 :meth:`serve_forever` method::
Georg Brandl48310cd2009-01-03 21:18:54 +00001162
Georg Brandl1f01deb2009-01-03 22:47:39 +00001163 >>> from multiprocessing.managers import BaseManager
R. David Murray8e8099c2009-04-28 18:02:00 +00001164 >>> manager = BaseManager(address=('', 50000), authkey='abc')
1165 >>> server = manager.get_server()
1166 >>> server.serve_forever()
Georg Brandl48310cd2009-01-03 21:18:54 +00001167
R. David Murray8e8099c2009-04-28 18:02:00 +00001168 :class:`Server` additionally has an :attr:`address` attribute.
Jesse Noller45239682008-11-28 18:46:19 +00001169
1170 .. method:: connect()
Georg Brandl48310cd2009-01-03 21:18:54 +00001171
R. David Murray8e8099c2009-04-28 18:02:00 +00001172 Connect a local manager object to a remote manager process::
Georg Brandl48310cd2009-01-03 21:18:54 +00001173
Jesse Noller45239682008-11-28 18:46:19 +00001174 >>> from multiprocessing.managers import BaseManager
R. David Murray8e8099c2009-04-28 18:02:00 +00001175 >>> m = BaseManager(address=('127.0.0.1', 5000), authkey='abc')
Jesse Noller45239682008-11-28 18:46:19 +00001176 >>> m.connect()
1177
Benjamin Petersone711caf2008-06-11 16:44:04 +00001178 .. method:: shutdown()
1179
1180 Stop the process used by the manager. This is only available if
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001181 :meth:`start` has been used to start the server process.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001182
1183 This can be called multiple times.
1184
1185 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1186
1187 A classmethod which can be used for registering a type or callable with
1188 the manager class.
1189
1190 *typeid* is a "type identifier" which is used to identify a particular
1191 type of shared object. This must be a string.
1192
1193 *callable* is a callable used for creating objects for this type
1194 identifier. If a manager instance will be created using the
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001195 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Petersone711caf2008-06-11 16:44:04 +00001196 ``False`` then this can be left as ``None``.
1197
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001198 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1199 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1200 class is created automatically.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001201
1202 *exposed* is used to specify a sequence of method names which proxies for
1203 this typeid should be allowed to access using
1204 :meth:`BaseProxy._callMethod`. (If *exposed* is ``None`` then
1205 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1206 where no exposed list is specified, all "public methods" of the shared
1207 object will be accessible. (Here a "public method" means any attribute
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001208 which has a :meth:`__call__` method and whose name does not begin with
Benjamin Petersone711caf2008-06-11 16:44:04 +00001209 ``'_'``.)
1210
1211 *method_to_typeid* is a mapping used to specify the return type of those
1212 exposed methods which should return a proxy. It maps method names to
1213 typeid strings. (If *method_to_typeid* is ``None`` then
1214 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1215 method's name is not a key of this mapping or if the mapping is ``None``
1216 then the object returned by the method will be copied by value.
1217
1218 *create_method* determines whether a method should be created with name
1219 *typeid* which can be used to tell the server process to create a new
1220 shared object and return a proxy for it. By default it is ``True``.
1221
1222 :class:`BaseManager` instances also have one read-only property:
1223
1224 .. attribute:: address
1225
1226 The address used by the manager.
1227
1228
1229.. class:: SyncManager
1230
1231 A subclass of :class:`BaseManager` which can be used for the synchronization
1232 of processes. Objects of this type are returned by
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001233 :func:`multiprocessing.Manager`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001234
1235 It also supports creation of shared lists and dictionaries.
1236
1237 .. method:: BoundedSemaphore([value])
1238
1239 Create a shared :class:`threading.BoundedSemaphore` object and return a
1240 proxy for it.
1241
1242 .. method:: Condition([lock])
1243
1244 Create a shared :class:`threading.Condition` object and return a proxy for
1245 it.
1246
1247 If *lock* is supplied then it should be a proxy for a
1248 :class:`threading.Lock` or :class:`threading.RLock` object.
1249
1250 .. method:: Event()
1251
1252 Create a shared :class:`threading.Event` object and return a proxy for it.
1253
1254 .. method:: Lock()
1255
1256 Create a shared :class:`threading.Lock` object and return a proxy for it.
1257
1258 .. method:: Namespace()
1259
1260 Create a shared :class:`Namespace` object and return a proxy for it.
1261
1262 .. method:: Queue([maxsize])
1263
Benjamin Peterson257060a2008-06-28 01:42:41 +00001264 Create a shared :class:`queue.Queue` object and return a proxy for it.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001265
1266 .. method:: RLock()
1267
1268 Create a shared :class:`threading.RLock` object and return a proxy for it.
1269
1270 .. method:: Semaphore([value])
1271
1272 Create a shared :class:`threading.Semaphore` object and return a proxy for
1273 it.
1274
1275 .. method:: Array(typecode, sequence)
1276
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001277 Create an array and return a proxy for it.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001278
1279 .. method:: Value(typecode, value)
1280
1281 Create an object with a writable ``value`` attribute and return a proxy
1282 for it.
1283
1284 .. method:: dict()
1285 dict(mapping)
1286 dict(sequence)
1287
1288 Create a shared ``dict`` object and return a proxy for it.
1289
1290 .. method:: list()
1291 list(sequence)
1292
1293 Create a shared ``list`` object and return a proxy for it.
1294
1295
1296Namespace objects
1297>>>>>>>>>>>>>>>>>
1298
1299A namespace object has no public methods, but does have writable attributes.
1300Its representation shows the values of its attributes.
1301
1302However, when using a proxy for a namespace object, an attribute beginning with
R. David Murray8e8099c2009-04-28 18:02:00 +00001303``'_'`` will be an attribute of the proxy and not an attribute of the referent:
1304
1305.. doctest::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001306
1307 >>> manager = multiprocessing.Manager()
1308 >>> Global = manager.Namespace()
1309 >>> Global.x = 10
1310 >>> Global.y = 'hello'
1311 >>> Global._z = 12.3 # this is an attribute of the proxy
Georg Brandl49702152008-09-29 06:43:45 +00001312 >>> print(Global)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001313 Namespace(x=10, y='hello')
1314
1315
1316Customized managers
1317>>>>>>>>>>>>>>>>>>>
1318
1319To create one's own manager, one creates a subclass of :class:`BaseManager` and
Georg Brandl1f01deb2009-01-03 22:47:39 +00001320use the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001321callables with the manager class. For example::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001322
1323 from multiprocessing.managers import BaseManager
1324
1325 class MathsClass(object):
1326 def add(self, x, y):
1327 return x + y
1328 def mul(self, x, y):
1329 return x * y
1330
1331 class MyManager(BaseManager):
1332 pass
1333
1334 MyManager.register('Maths', MathsClass)
1335
1336 if __name__ == '__main__':
1337 manager = MyManager()
1338 manager.start()
1339 maths = manager.Maths()
Georg Brandl49702152008-09-29 06:43:45 +00001340 print(maths.add(4, 3)) # prints 7
1341 print(maths.mul(7, 8)) # prints 56
Benjamin Petersone711caf2008-06-11 16:44:04 +00001342
1343
1344Using a remote manager
1345>>>>>>>>>>>>>>>>>>>>>>
1346
1347It is possible to run a manager server on one machine and have clients use it
1348from other machines (assuming that the firewalls involved allow it).
1349
1350Running the following commands creates a server for a single shared queue which
1351remote clients can access::
1352
1353 >>> from multiprocessing.managers import BaseManager
Benjamin Peterson257060a2008-06-28 01:42:41 +00001354 >>> import queue
1355 >>> queue = queue.Queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001356 >>> class QueueManager(BaseManager): pass
Jesse Noller45239682008-11-28 18:46:19 +00001357 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001358 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Noller45239682008-11-28 18:46:19 +00001359 >>> s = m.get_server()
R. David Murray8e8099c2009-04-28 18:02:00 +00001360 >>> s.serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001361
1362One client can access the server as follows::
1363
1364 >>> from multiprocessing.managers import BaseManager
1365 >>> class QueueManager(BaseManager): pass
Jesse Noller45239682008-11-28 18:46:19 +00001366 >>> QueueManager.register('get_queue')
1367 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1368 >>> m.connect()
1369 >>> queue = m.get_queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001370 >>> queue.put('hello')
1371
1372Another client can also use it::
1373
1374 >>> from multiprocessing.managers import BaseManager
1375 >>> class QueueManager(BaseManager): pass
R. David Murray8e8099c2009-04-28 18:02:00 +00001376 >>> QueueManager.register('get_queue')
1377 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1378 >>> m.connect()
1379 >>> queue = m.get_queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001380 >>> queue.get()
1381 'hello'
1382
Georg Brandl48310cd2009-01-03 21:18:54 +00001383Local processes can also access that queue, using the code from above on the
Jesse Noller45239682008-11-28 18:46:19 +00001384client to access it remotely::
1385
1386 >>> from multiprocessing import Process, Queue
1387 >>> from multiprocessing.managers import BaseManager
1388 >>> class Worker(Process):
1389 ... def __init__(self, q):
1390 ... self.q = q
1391 ... super(Worker, self).__init__()
1392 ... def run(self):
1393 ... self.q.put('local hello')
Georg Brandl48310cd2009-01-03 21:18:54 +00001394 ...
Jesse Noller45239682008-11-28 18:46:19 +00001395 >>> queue = Queue()
1396 >>> w = Worker(queue)
1397 >>> w.start()
1398 >>> class QueueManager(BaseManager): pass
Georg Brandl48310cd2009-01-03 21:18:54 +00001399 ...
Jesse Noller45239682008-11-28 18:46:19 +00001400 >>> QueueManager.register('get_queue', callable=lambda: queue)
1401 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1402 >>> s = m.get_server()
1403 >>> s.serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001404
1405Proxy Objects
1406~~~~~~~~~~~~~
1407
1408A proxy is an object which *refers* to a shared object which lives (presumably)
1409in a different process. The shared object is said to be the *referent* of the
1410proxy. Multiple proxy objects may have the same referent.
1411
1412A proxy object has methods which invoke corresponding methods of its referent
1413(although not every method of the referent will necessarily be available through
1414the proxy). A proxy can usually be used in most of the same ways that its
R. David Murray8e8099c2009-04-28 18:02:00 +00001415referent can:
1416
1417.. doctest::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001418
1419 >>> from multiprocessing import Manager
1420 >>> manager = Manager()
1421 >>> l = manager.list([i*i for i in range(10)])
Georg Brandl49702152008-09-29 06:43:45 +00001422 >>> print(l)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001423 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Georg Brandl49702152008-09-29 06:43:45 +00001424 >>> print(repr(l))
R. David Murray8e8099c2009-04-28 18:02:00 +00001425 <ListProxy object, typeid 'list' at 0x...>
Benjamin Petersone711caf2008-06-11 16:44:04 +00001426 >>> l[4]
1427 16
1428 >>> l[2:5]
1429 [4, 9, 16]
1430
1431Notice that applying :func:`str` to a proxy will return the representation of
1432the referent, whereas applying :func:`repr` will return the representation of
1433the proxy.
1434
1435An important feature of proxy objects is that they are picklable so they can be
1436passed between processes. Note, however, that if a proxy is sent to the
1437corresponding manager's process then unpickling it will produce the referent
R. David Murray8e8099c2009-04-28 18:02:00 +00001438itself. This means, for example, that one shared object can contain a second:
1439
1440.. doctest::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001441
1442 >>> a = manager.list()
1443 >>> b = manager.list()
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001444 >>> a.append(b) # referent of a now contains referent of b
Georg Brandl49702152008-09-29 06:43:45 +00001445 >>> print(a, b)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001446 [[]] []
1447 >>> b.append('hello')
Georg Brandl49702152008-09-29 06:43:45 +00001448 >>> print(a, b)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001449 [['hello']] ['hello']
1450
1451.. note::
1452
1453 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
R. David Murray8e8099c2009-04-28 18:02:00 +00001454 by value. So, for instance, we have:
Benjamin Petersone711caf2008-06-11 16:44:04 +00001455
R. David Murray8e8099c2009-04-28 18:02:00 +00001456 .. doctest::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001457
R. David Murray8e8099c2009-04-28 18:02:00 +00001458 >>> manager.list([1,2,3]) == [1,2,3]
1459 False
1460
1461 One should just use a copy of the referent instead when making comparisons.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001462
1463.. class:: BaseProxy
1464
1465 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1466
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001467 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001468
1469 Call and return the result of a method of the proxy's referent.
1470
1471 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1472
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001473 proxy._callmethod(methodname, args, kwds)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001474
1475 will evaluate the expression ::
1476
1477 getattr(obj, methodname)(*args, **kwds)
1478
1479 in the manager's process.
1480
1481 The returned value will be a copy of the result of the call or a proxy to
1482 a new shared object -- see documentation for the *method_to_typeid*
1483 argument of :meth:`BaseManager.register`.
1484
1485 If an exception is raised by the call, then then is re-raised by
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001486 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Petersone711caf2008-06-11 16:44:04 +00001487 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001488 raised by :meth:`_callmethod`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001489
1490 Note in particular that an exception will be raised if *methodname* has
1491 not been *exposed*
1492
R. David Murray8e8099c2009-04-28 18:02:00 +00001493 An example of the usage of :meth:`_callmethod`:
1494
1495 .. doctest::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001496
1497 >>> l = manager.list(range(10))
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001498 >>> l._callmethod('__len__')
Benjamin Petersone711caf2008-06-11 16:44:04 +00001499 10
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001500 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Petersone711caf2008-06-11 16:44:04 +00001501 [2, 3, 4, 5, 6]
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001502 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Petersone711caf2008-06-11 16:44:04 +00001503 Traceback (most recent call last):
1504 ...
1505 IndexError: list index out of range
1506
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001507 .. method:: _getvalue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001508
1509 Return a copy of the referent.
1510
1511 If the referent is unpicklable then this will raise an exception.
1512
1513 .. method:: __repr__
1514
1515 Return a representation of the proxy object.
1516
1517 .. method:: __str__
1518
1519 Return the representation of the referent.
1520
1521
1522Cleanup
1523>>>>>>>
1524
1525A proxy object uses a weakref callback so that when it gets garbage collected it
1526deregisters itself from the manager which owns its referent.
1527
1528A shared object gets deleted from the manager process when there are no longer
1529any proxies referring to it.
1530
1531
1532Process Pools
1533~~~~~~~~~~~~~
1534
1535.. module:: multiprocessing.pool
1536 :synopsis: Create pools of processes.
1537
1538One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001539with the :class:`Pool` class.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001540
1541.. class:: multiprocessing.Pool([processes[, initializer[, initargs]]])
1542
1543 A process pool object which controls a pool of worker processes to which jobs
1544 can be submitted. It supports asynchronous results with timeouts and
1545 callbacks and has a parallel map implementation.
1546
1547 *processes* is the number of worker processes to use. If *processes* is
1548 ``None`` then the number returned by :func:`cpu_count` is used. If
1549 *initializer* is not ``None`` then each worker process will call
1550 ``initializer(*initargs)`` when it starts.
1551
1552 .. method:: apply(func[, args[, kwds]])
1553
Benjamin Peterson37d2fe02008-10-24 22:28:58 +00001554 Call *func* with arguments *args* and keyword arguments *kwds*. It blocks
Jesse Noller7b3c89d2009-01-22 21:56:13 +00001555 till the result is ready. Given this blocks - :meth:`apply_async` is better suited
1556 for performing work in parallel. Additionally, the passed
1557 in function is only executed in one of the workers of the pool.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001558
1559 .. method:: apply_async(func[, args[, kwds[, callback]]])
1560
1561 A variant of the :meth:`apply` method which returns a result object.
1562
1563 If *callback* is specified then it should be a callable which accepts a
1564 single argument. When the result becomes ready *callback* is applied to
1565 it (unless the call failed). *callback* should complete immediately since
1566 otherwise the thread which handles the results will get blocked.
1567
1568 .. method:: map(func, iterable[, chunksize])
1569
Benjamin Petersond23f8222009-04-05 19:13:16 +00001570 A parallel equivalent of the :func:`map` builtin function (it supports only
1571 one *iterable* argument though). It blocks till the result is ready.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001572
1573 This method chops the iterable into a number of chunks which it submits to
1574 the process pool as separate tasks. The (approximate) size of these
1575 chunks can be specified by setting *chunksize* to a positive integer.
1576
1577 .. method:: map_async(func, iterable[, chunksize[, callback]])
1578
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001579 A variant of the :meth:`map` method which returns a result object.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001580
1581 If *callback* is specified then it should be a callable which accepts a
1582 single argument. When the result becomes ready *callback* is applied to
1583 it (unless the call failed). *callback* should complete immediately since
1584 otherwise the thread which handles the results will get blocked.
1585
1586 .. method:: imap(func, iterable[, chunksize])
1587
Georg Brandl92905032008-11-22 08:51:39 +00001588 A lazier version of :meth:`map`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001589
1590 The *chunksize* argument is the same as the one used by the :meth:`.map`
1591 method. For very long iterables using a large value for *chunksize* can
1592 make make the job complete **much** faster than using the default value of
1593 ``1``.
1594
1595 Also if *chunksize* is ``1`` then the :meth:`next` method of the iterator
1596 returned by the :meth:`imap` method has an optional *timeout* parameter:
1597 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1598 result cannot be returned within *timeout* seconds.
1599
1600 .. method:: imap_unordered(func, iterable[, chunksize])
1601
1602 The same as :meth:`imap` except that the ordering of the results from the
1603 returned iterator should be considered arbitrary. (Only when there is
1604 only one worker process is the order guaranteed to be "correct".)
1605
1606 .. method:: close()
1607
1608 Prevents any more tasks from being submitted to the pool. Once all the
1609 tasks have been completed the worker processes will exit.
1610
1611 .. method:: terminate()
1612
1613 Stops the worker processes immediately without completing outstanding
1614 work. When the pool object is garbage collected :meth:`terminate` will be
1615 called immediately.
1616
1617 .. method:: join()
1618
1619 Wait for the worker processes to exit. One must call :meth:`close` or
1620 :meth:`terminate` before using :meth:`join`.
1621
1622
1623.. class:: AsyncResult
1624
1625 The class of the result returned by :meth:`Pool.apply_async` and
1626 :meth:`Pool.map_async`.
1627
Georg Brandle3d70ae2008-11-22 08:54:21 +00001628 .. method:: get([timeout])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001629
1630 Return the result when it arrives. If *timeout* is not ``None`` and the
1631 result does not arrive within *timeout* seconds then
1632 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1633 an exception then that exception will be reraised by :meth:`get`.
1634
1635 .. method:: wait([timeout])
1636
1637 Wait until the result is available or until *timeout* seconds pass.
1638
1639 .. method:: ready()
1640
1641 Return whether the call has completed.
1642
1643 .. method:: successful()
1644
1645 Return whether the call completed without raising an exception. Will
1646 raise :exc:`AssertionError` if the result is not ready.
1647
1648The following example demonstrates the use of a pool::
1649
1650 from multiprocessing import Pool
1651
1652 def f(x):
1653 return x*x
1654
1655 if __name__ == '__main__':
1656 pool = Pool(processes=4) # start 4 worker processes
1657
Georg Brandle3d70ae2008-11-22 08:54:21 +00001658 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Georg Brandl49702152008-09-29 06:43:45 +00001659 print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow
Benjamin Petersone711caf2008-06-11 16:44:04 +00001660
Georg Brandl49702152008-09-29 06:43:45 +00001661 print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]"
Benjamin Petersone711caf2008-06-11 16:44:04 +00001662
1663 it = pool.imap(f, range(10))
Georg Brandl49702152008-09-29 06:43:45 +00001664 print(next(it)) # prints "0"
1665 print(next(it)) # prints "1"
1666 print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow
Benjamin Petersone711caf2008-06-11 16:44:04 +00001667
1668 import time
Georg Brandle3d70ae2008-11-22 08:54:21 +00001669 result = pool.apply_async(time.sleep, (10,))
Georg Brandl49702152008-09-29 06:43:45 +00001670 print(result.get(timeout=1)) # raises TimeoutError
Benjamin Petersone711caf2008-06-11 16:44:04 +00001671
1672
1673.. _multiprocessing-listeners-clients:
1674
1675Listeners and Clients
1676~~~~~~~~~~~~~~~~~~~~~
1677
1678.. module:: multiprocessing.connection
1679 :synopsis: API for dealing with sockets.
1680
1681Usually message passing between processes is done using queues or by using
1682:class:`Connection` objects returned by :func:`Pipe`.
1683
1684However, the :mod:`multiprocessing.connection` module allows some extra
1685flexibility. It basically gives a high level message oriented API for dealing
1686with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001687authentication* using the :mod:`hmac` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001688
1689
1690.. function:: deliver_challenge(connection, authkey)
1691
1692 Send a randomly generated message to the other end of the connection and wait
1693 for a reply.
1694
1695 If the reply matches the digest of the message using *authkey* as the key
1696 then a welcome message is sent to the other end of the connection. Otherwise
1697 :exc:`AuthenticationError` is raised.
1698
1699.. function:: answerChallenge(connection, authkey)
1700
1701 Receive a message, calculate the digest of the message using *authkey* as the
1702 key, and then send the digest back.
1703
1704 If a welcome message is not received, then :exc:`AuthenticationError` is
1705 raised.
1706
1707.. function:: Client(address[, family[, authenticate[, authkey]]])
1708
1709 Attempt to set up a connection to the listener which is using address
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001710 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001711
1712 The type of the connection is determined by *family* argument, but this can
1713 generally be omitted since it can usually be inferred from the format of
1714 *address*. (See :ref:`multiprocessing-address-formats`)
1715
1716 If *authentication* is ``True`` or *authkey* is a string then digest
1717 authentication is used. The key used for authentication will be either
Benjamin Petersona786b022008-08-25 21:05:21 +00001718 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001719 If authentication fails then :exc:`AuthenticationError` is raised. See
1720 :ref:`multiprocessing-auth-keys`.
1721
1722.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1723
1724 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1725 connections.
1726
1727 *address* is the address to be used by the bound socket or named pipe of the
1728 listener object.
1729
Benjamin Petersond23f8222009-04-05 19:13:16 +00001730 .. note::
1731
1732 If an address of '0.0.0.0' is used, the address will not be a connectable
1733 end point on Windows. If you require a connectable end-point,
1734 you should use '127.0.0.1'.
1735
Benjamin Petersone711caf2008-06-11 16:44:04 +00001736 *family* is the type of socket (or named pipe) to use. This can be one of
1737 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1738 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1739 the first is guaranteed to be available. If *family* is ``None`` then the
1740 family is inferred from the format of *address*. If *address* is also
1741 ``None`` then a default is chosen. This default is the family which is
1742 assumed to be the fastest available. See
1743 :ref:`multiprocessing-address-formats`. Note that if *family* is
1744 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1745 private temporary directory created using :func:`tempfile.mkstemp`.
1746
1747 If the listener object uses a socket then *backlog* (1 by default) is passed
1748 to the :meth:`listen` method of the socket once it has been bound.
1749
1750 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1751 ``None`` then digest authentication is used.
1752
1753 If *authkey* is a string then it will be used as the authentication key;
1754 otherwise it must be *None*.
1755
1756 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Petersona786b022008-08-25 21:05:21 +00001757 ``current_process().authkey`` is used as the authentication key. If
Benjamin Petersone711caf2008-06-11 16:44:04 +00001758 *authkey* is ``None`` and *authentication* is ``False`` then no
1759 authentication is done. If authentication fails then
1760 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1761
1762 .. method:: accept()
1763
1764 Accept a connection on the bound socket or named pipe of the listener
1765 object and return a :class:`Connection` object. If authentication is
1766 attempted and fails, then :exc:`AuthenticationError` is raised.
1767
1768 .. method:: close()
1769
1770 Close the bound socket or named pipe of the listener object. This is
1771 called automatically when the listener is garbage collected. However it
1772 is advisable to call it explicitly.
1773
1774 Listener objects have the following read-only properties:
1775
1776 .. attribute:: address
1777
1778 The address which is being used by the Listener object.
1779
1780 .. attribute:: last_accepted
1781
1782 The address from which the last accepted connection came. If this is
1783 unavailable then it is ``None``.
1784
1785
1786The module defines two exceptions:
1787
1788.. exception:: AuthenticationError
1789
1790 Exception raised when there is an authentication error.
1791
Benjamin Petersone711caf2008-06-11 16:44:04 +00001792
1793**Examples**
1794
1795The following server code creates a listener which uses ``'secret password'`` as
1796an authentication key. It then waits for a connection and sends some data to
1797the client::
1798
1799 from multiprocessing.connection import Listener
1800 from array import array
1801
1802 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
1803 listener = Listener(address, authkey='secret password')
1804
1805 conn = listener.accept()
Georg Brandl49702152008-09-29 06:43:45 +00001806 print('connection accepted from', listener.last_accepted)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001807
1808 conn.send([2.25, None, 'junk', float])
1809
1810 conn.send_bytes('hello')
1811
1812 conn.send_bytes(array('i', [42, 1729]))
1813
1814 conn.close()
1815 listener.close()
1816
1817The following code connects to the server and receives some data from the
1818server::
1819
1820 from multiprocessing.connection import Client
1821 from array import array
1822
1823 address = ('localhost', 6000)
1824 conn = Client(address, authkey='secret password')
1825
Georg Brandl49702152008-09-29 06:43:45 +00001826 print(conn.recv()) # => [2.25, None, 'junk', float]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001827
Georg Brandl49702152008-09-29 06:43:45 +00001828 print(conn.recv_bytes()) # => 'hello'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001829
1830 arr = array('i', [0, 0, 0, 0, 0])
Georg Brandl49702152008-09-29 06:43:45 +00001831 print(conn.recv_bytes_into(arr)) # => 8
1832 print(arr) # => array('i', [42, 1729, 0, 0, 0])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001833
1834 conn.close()
1835
1836
1837.. _multiprocessing-address-formats:
1838
1839Address Formats
1840>>>>>>>>>>>>>>>
1841
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001842* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Petersone711caf2008-06-11 16:44:04 +00001843 *hostname* is a string and *port* is an integer.
1844
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001845* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Petersone711caf2008-06-11 16:44:04 +00001846 filesystem.
1847
1848* An ``'AF_PIPE'`` address is a string of the form
Benjamin Petersonda10d3b2009-01-01 00:23:30 +00001849 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandl1f01deb2009-01-03 22:47:39 +00001850 pipe on a remote computer called *ServerName* one should use an address of the
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001851 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001852
1853Note that any string beginning with two backslashes is assumed by default to be
1854an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
1855
1856
1857.. _multiprocessing-auth-keys:
1858
1859Authentication keys
1860~~~~~~~~~~~~~~~~~~~
1861
1862When one uses :meth:`Connection.recv`, the data received is automatically
1863unpickled. Unfortunately unpickling data from an untrusted source is a security
1864risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
1865to provide digest authentication.
1866
1867An authentication key is a string which can be thought of as a password: once a
1868connection is established both ends will demand proof that the other knows the
1869authentication key. (Demonstrating that both ends are using the same key does
1870**not** involve sending the key over the connection.)
1871
1872If authentication is requested but do authentication key is specified then the
Benjamin Petersona786b022008-08-25 21:05:21 +00001873return value of ``current_process().authkey`` is used (see
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001874:class:`~multiprocessing.Process`). This value will automatically inherited by
1875any :class:`~multiprocessing.Process` object that the current process creates.
1876This means that (by default) all processes of a multi-process program will share
1877a single authentication key which can be used when setting up connections
Benjamin Petersond23f8222009-04-05 19:13:16 +00001878between themselves.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001879
1880Suitable authentication keys can also be generated by using :func:`os.urandom`.
1881
1882
1883Logging
1884~~~~~~~
1885
1886Some support for logging is available. Note, however, that the :mod:`logging`
1887package does not use process shared locks so it is possible (depending on the
1888handler type) for messages from different processes to get mixed up.
1889
1890.. currentmodule:: multiprocessing
1891.. function:: get_logger()
1892
1893 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
1894 will be created.
1895
Jesse Noller41faa542009-01-25 03:45:53 +00001896 When first created the logger has level :data:`logging.NOTSET` and no
1897 default handler. Messages sent to this logger will not by default propagate
1898 to the root logger.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001899
1900 Note that on Windows child processes will only inherit the level of the
1901 parent process's logger -- any other customization of the logger will not be
1902 inherited.
1903
Jesse Noller41faa542009-01-25 03:45:53 +00001904.. currentmodule:: multiprocessing
1905.. function:: log_to_stderr()
1906
1907 This function performs a call to :func:`get_logger` but in addition to
1908 returning the logger created by get_logger, it adds a handler which sends
1909 output to :data:`sys.stderr` using format
1910 ``'[%(levelname)s/%(processName)s] %(message)s'``.
1911
Benjamin Petersone711caf2008-06-11 16:44:04 +00001912Below is an example session with logging turned on::
1913
Benjamin Peterson206e3072008-10-19 14:07:49 +00001914 >>> import multiprocessing, logging
Jesse Noller41faa542009-01-25 03:45:53 +00001915 >>> logger = multiprocessing.log_to_stderr()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001916 >>> logger.setLevel(logging.INFO)
1917 >>> logger.warning('doomed')
1918 [WARNING/MainProcess] doomed
Benjamin Peterson206e3072008-10-19 14:07:49 +00001919 >>> m = multiprocessing.Manager()
R. David Murray8e8099c2009-04-28 18:02:00 +00001920 [INFO/SyncManager-...] child process calling self.run()
1921 [INFO/SyncManager-...] created temp directory /.../pymp-...
1922 [INFO/SyncManager-...] manager serving at '/.../listener-...'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001923 >>> del m
1924 [INFO/MainProcess] sending shutdown message to manager
R. David Murray8e8099c2009-04-28 18:02:00 +00001925 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Petersone711caf2008-06-11 16:44:04 +00001926
Jesse Noller41faa542009-01-25 03:45:53 +00001927In addition to having these two logging functions, the multiprocessing also
1928exposes two additional logging level attributes. These are :const:`SUBWARNING`
1929and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
1930normal level hierarchy.
1931
1932+----------------+----------------+
1933| Level | Numeric value |
1934+================+================+
1935| ``SUBWARNING`` | 25 |
1936+----------------+----------------+
1937| ``SUBDEBUG`` | 5 |
1938+----------------+----------------+
1939
1940For a full table of logging levels, see the :mod:`logging` module.
1941
1942These additional logging levels are used primarily for certain debug messages
1943within the multiprocessing module. Below is the same example as above, except
1944with :const:`SUBDEBUG` enabled::
1945
1946 >>> import multiprocessing, logging
1947 >>> logger = multiprocessing.log_to_stderr()
1948 >>> logger.setLevel(multiprocessing.SUBDEBUG)
1949 >>> logger.warning('doomed')
1950 [WARNING/MainProcess] doomed
1951 >>> m = multiprocessing.Manager()
R. David Murray8e8099c2009-04-28 18:02:00 +00001952 [INFO/SyncManager-...] child process calling self.run()
1953 [INFO/SyncManager-...] created temp directory /.../pymp-...
1954 [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
Jesse Noller41faa542009-01-25 03:45:53 +00001955 >>> del m
1956 [SUBDEBUG/MainProcess] finalizer calling ...
1957 [INFO/MainProcess] sending shutdown message to manager
R. David Murray8e8099c2009-04-28 18:02:00 +00001958 [DEBUG/SyncManager-...] manager received shutdown message
1959 [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
1960 [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
1961 [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
1962 [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
1963 [INFO/SyncManager-...] manager exiting with exitcode 0
Benjamin Petersone711caf2008-06-11 16:44:04 +00001964
1965The :mod:`multiprocessing.dummy` module
1966~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1967
1968.. module:: multiprocessing.dummy
1969 :synopsis: Dumb wrapper around threading.
1970
1971:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001972no more than a wrapper around the :mod:`threading` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001973
1974
1975.. _multiprocessing-programming:
1976
1977Programming guidelines
1978----------------------
1979
1980There are certain guidelines and idioms which should be adhered to when using
1981:mod:`multiprocessing`.
1982
1983
1984All platforms
1985~~~~~~~~~~~~~
1986
1987Avoid shared state
1988
1989 As far as possible one should try to avoid shifting large amounts of data
1990 between processes.
1991
1992 It is probably best to stick to using queues or pipes for communication
1993 between processes rather than using the lower level synchronization
1994 primitives from the :mod:`threading` module.
1995
1996Picklability
1997
1998 Ensure that the arguments to the methods of proxies are picklable.
1999
2000Thread safety of proxies
2001
2002 Do not use a proxy object from more than one thread unless you protect it
2003 with a lock.
2004
2005 (There is never a problem with different processes using the *same* proxy.)
2006
2007Joining zombie processes
2008
2009 On Unix when a process finishes but has not been joined it becomes a zombie.
2010 There should never be very many because each time a new process starts (or
2011 :func:`active_children` is called) all completed processes which have not
2012 yet been joined will be joined. Also calling a finished process's
2013 :meth:`Process.is_alive` will join the process. Even so it is probably good
2014 practice to explicitly join all the processes that you start.
2015
2016Better to inherit than pickle/unpickle
2017
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002018 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Petersone711caf2008-06-11 16:44:04 +00002019 that child processes can use them. However, one should generally avoid
2020 sending shared objects to other processes using pipes or queues. Instead
2021 you should arrange the program so that a process which need access to a
2022 shared resource created elsewhere can inherit it from an ancestor process.
2023
2024Avoid terminating processes
2025
2026 Using the :meth:`Process.terminate` method to stop a process is liable to
2027 cause any shared resources (such as locks, semaphores, pipes and queues)
2028 currently being used by the process to become broken or unavailable to other
2029 processes.
2030
2031 Therefore it is probably best to only consider using
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002032 :meth:`Process.terminate` on processes which never use any shared resources.
Benjamin Petersone711caf2008-06-11 16:44:04 +00002033
2034Joining processes that use queues
2035
2036 Bear in mind that a process that has put items in a queue will wait before
2037 terminating until all the buffered items are fed by the "feeder" thread to
2038 the underlying pipe. (The child process can call the
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002039 :meth:`Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Petersone711caf2008-06-11 16:44:04 +00002040
2041 This means that whenever you use a queue you need to make sure that all
2042 items which have been put on the queue will eventually be removed before the
2043 process is joined. Otherwise you cannot be sure that processes which have
2044 put items on the queue will terminate. Remember also that non-daemonic
2045 processes will be automatically be joined.
2046
2047 An example which will deadlock is the following::
2048
2049 from multiprocessing import Process, Queue
2050
2051 def f(q):
2052 q.put('X' * 1000000)
2053
2054 if __name__ == '__main__':
2055 queue = Queue()
2056 p = Process(target=f, args=(queue,))
2057 p.start()
2058 p.join() # this deadlocks
2059 obj = queue.get()
2060
2061 A fix here would be to swap the last two lines round (or simply remove the
2062 ``p.join()`` line).
2063
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002064Explicitly pass resources to child processes
Benjamin Petersone711caf2008-06-11 16:44:04 +00002065
2066 On Unix a child process can make use of a shared resource created in a
2067 parent process using a global resource. However, it is better to pass the
2068 object as an argument to the constructor for the child process.
2069
2070 Apart from making the code (potentially) compatible with Windows this also
2071 ensures that as long as the child process is still alive the object will not
2072 be garbage collected in the parent process. This might be important if some
2073 resource is freed when the object is garbage collected in the parent
2074 process.
2075
2076 So for instance ::
2077
2078 from multiprocessing import Process, Lock
2079
2080 def f():
2081 ... do something using "lock" ...
2082
2083 if __name__ == '__main__':
2084 lock = Lock()
2085 for i in range(10):
2086 Process(target=f).start()
2087
2088 should be rewritten as ::
2089
2090 from multiprocessing import Process, Lock
2091
2092 def f(l):
2093 ... do something using "l" ...
2094
2095 if __name__ == '__main__':
2096 lock = Lock()
2097 for i in range(10):
2098 Process(target=f, args=(lock,)).start()
2099
2100
2101Windows
2102~~~~~~~
2103
2104Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2105
2106More picklability
2107
2108 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2109 means, in particular, that bound or unbound methods cannot be used directly
2110 as the ``target`` argument on Windows --- just define a function and use
2111 that instead.
2112
2113 Also, if you subclass :class:`Process` then make sure that instances will be
2114 picklable when the :meth:`Process.start` method is called.
2115
2116Global variables
2117
2118 Bear in mind that if code run in a child process tries to access a global
2119 variable, then the value it sees (if any) may not be the same as the value
2120 in the parent process at the time that :meth:`Process.start` was called.
2121
2122 However, global variables which are just module level constants cause no
2123 problems.
2124
2125Safe importing of main module
2126
2127 Make sure that the main module can be safely imported by a new Python
2128 interpreter without causing unintended side effects (such a starting a new
2129 process).
2130
2131 For example, under Windows running the following module would fail with a
2132 :exc:`RuntimeError`::
2133
2134 from multiprocessing import Process
2135
2136 def foo():
Georg Brandl49702152008-09-29 06:43:45 +00002137 print('hello')
Benjamin Petersone711caf2008-06-11 16:44:04 +00002138
2139 p = Process(target=foo)
2140 p.start()
2141
2142 Instead one should protect the "entry point" of the program by using ``if
2143 __name__ == '__main__':`` as follows::
2144
2145 from multiprocessing import Process, freeze_support
2146
2147 def foo():
Georg Brandl49702152008-09-29 06:43:45 +00002148 print('hello')
Benjamin Petersone711caf2008-06-11 16:44:04 +00002149
2150 if __name__ == '__main__':
2151 freeze_support()
2152 p = Process(target=foo)
2153 p.start()
2154
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002155 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Petersone711caf2008-06-11 16:44:04 +00002156 normally instead of frozen.)
2157
2158 This allows the newly spawned Python interpreter to safely import the module
2159 and then run the module's ``foo()`` function.
2160
2161 Similar restrictions apply if a pool or manager is created in the main
2162 module.
2163
2164
2165.. _multiprocessing-examples:
2166
2167Examples
2168--------
2169
2170Demonstration of how to create and use customized managers and proxies:
2171
2172.. literalinclude:: ../includes/mp_newtype.py
2173
2174
2175Using :class:`Pool`:
2176
2177.. literalinclude:: ../includes/mp_pool.py
2178
2179
2180Synchronization types like locks, conditions and queues:
2181
2182.. literalinclude:: ../includes/mp_synchronize.py
2183
2184
2185An showing how to use queues to feed tasks to a collection of worker process and
2186collect the results:
2187
2188.. literalinclude:: ../includes/mp_workers.py
2189
2190
2191An example of how a pool of worker processes can each run a
2192:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2193socket.
2194
2195.. literalinclude:: ../includes/mp_webserver.py
2196
2197
2198Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2199
2200.. literalinclude:: ../includes/mp_benchmarks.py
2201
2202An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process`
Georg Brandl48310cd2009-01-03 21:18:54 +00002203and others to build a system which can distribute processes and work via a
Benjamin Petersone711caf2008-06-11 16:44:04 +00002204distributed queue to a "cluster" of machines on a network, accessible via SSH.
2205You will need to have private key authentication for all hosts configured for
2206this to work.
2207
Benjamin Peterson95a939c2008-06-14 02:23:29 +00002208.. literalinclude:: ../includes/mp_distributing.py