blob: 53d8981512173eb16ae44c99ee9cb0a10d5a6723 [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:
43 Traceback (most recent call last):
44 Traceback (most recent call last):
45 AttributeError: 'module' object has no attribute 'f'
46 AttributeError: 'module' object has no attribute 'f'
47 AttributeError: 'module' object has no attribute 'f'
48
49
Benjamin Petersone711caf2008-06-11 16:44:04 +000050The :class:`Process` class
51~~~~~~~~~~~~~~~~~~~~~~~~~~
52
53In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
Benjamin Peterson5289b2b2008-06-28 00:40:54 +000054object and then calling its :meth:`~Process.start` method. :class:`Process`
Benjamin Petersone711caf2008-06-11 16:44:04 +000055follows the API of :class:`threading.Thread`. A trivial example of a
56multiprocess program is ::
57
Jesse Noller45239682008-11-28 18:46:19 +000058 from multiprocessing import Process
Benjamin Petersone711caf2008-06-11 16:44:04 +000059
60 def f(name):
Georg Brandl49702152008-09-29 06:43:45 +000061 print('hello', name)
Benjamin Petersone711caf2008-06-11 16:44:04 +000062
Jesse Noller45239682008-11-28 18:46:19 +000063 if __name__ == '__main__':
64 p = Process(target=f, args=('bob',))
65 p.start()
66 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +000067
Jesse Noller45239682008-11-28 18:46:19 +000068To show the individual process IDs involved, here is an expanded example::
69
70 from multiprocessing import Process
71 import os
72
73 def info(title):
74 print title
75 print 'module name:', __name__
76 print 'parent process:', os.getppid()
77 print 'process id:', os.getpid()
Georg Brandl48310cd2009-01-03 21:18:54 +000078
Jesse Noller45239682008-11-28 18:46:19 +000079 def f(name):
80 info('function f')
81 print 'hello', name
Georg Brandl48310cd2009-01-03 21:18:54 +000082
Jesse Noller45239682008-11-28 18:46:19 +000083 if __name__ == '__main__':
84 info('main line')
85 p = Process(target=f, args=('bob',))
86 p.start()
87 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +000088
89For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is
90necessary, see :ref:`multiprocessing-programming`.
91
92
93
94Exchanging objects between processes
95~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
96
97:mod:`multiprocessing` supports two types of communication channel between
98processes:
99
100**Queues**
101
Benjamin Peterson257060a2008-06-28 01:42:41 +0000102 The :class:`Queue` class is a near clone of :class:`queue.Queue`. For
Benjamin Petersone711caf2008-06-11 16:44:04 +0000103 example::
104
105 from multiprocessing import Process, Queue
106
107 def f(q):
108 q.put([42, None, 'hello'])
109
Georg Brandl1f01deb2009-01-03 22:47:39 +0000110 if __name__ == '__main__':
111 q = Queue()
112 p = Process(target=f, args=(q,))
113 p.start()
114 print(q.get()) # prints "[42, None, 'hello']"
115 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000116
117 Queues are thread and process safe.
118
119**Pipes**
120
121 The :func:`Pipe` function returns a pair of connection objects connected by a
122 pipe which by default is duplex (two-way). For example::
123
124 from multiprocessing import Process, Pipe
125
126 def f(conn):
127 conn.send([42, None, 'hello'])
128 conn.close()
129
130 if __name__ == '__main__':
131 parent_conn, child_conn = Pipe()
132 p = Process(target=f, args=(child_conn,))
133 p.start()
Georg Brandl49702152008-09-29 06:43:45 +0000134 print(parent_conn.recv()) # prints "[42, None, 'hello']"
Benjamin Petersone711caf2008-06-11 16:44:04 +0000135 p.join()
136
137 The two connection objects returned by :func:`Pipe` represent the two ends of
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000138 the pipe. Each connection object has :meth:`~Connection.send` and
139 :meth:`~Connection.recv` methods (among others). Note that data in a pipe
140 may become corrupted if two processes (or threads) try to read from or write
141 to the *same* end of the pipe at the same time. Of course there is no risk
142 of corruption from processes using different ends of the pipe at the same
143 time.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000144
145
146Synchronization between processes
147~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148
149:mod:`multiprocessing` contains equivalents of all the synchronization
150primitives from :mod:`threading`. For instance one can use a lock to ensure
151that only one process prints to standard output at a time::
152
153 from multiprocessing import Process, Lock
154
155 def f(l, i):
156 l.acquire()
Georg Brandl49702152008-09-29 06:43:45 +0000157 print('hello world', i)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000158 l.release()
159
160 if __name__ == '__main__':
161 lock = Lock()
162
163 for num in range(10):
164 Process(target=f, args=(lock, num)).start()
165
166Without using the lock output from the different processes is liable to get all
167mixed up.
168
169
170Sharing state between processes
171~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
172
173As mentioned above, when doing concurrent programming it is usually best to
174avoid using shared state as far as possible. This is particularly true when
175using multiple processes.
176
177However, if you really do need to use some shared data then
178:mod:`multiprocessing` provides a couple of ways of doing so.
179
180**Shared memory**
181
182 Data can be stored in a shared memory map using :class:`Value` or
183 :class:`Array`. For example, the following code ::
184
185 from multiprocessing import Process, Value, Array
186
187 def f(n, a):
188 n.value = 3.1415927
189 for i in range(len(a)):
190 a[i] = -a[i]
191
192 if __name__ == '__main__':
193 num = Value('d', 0.0)
194 arr = Array('i', range(10))
195
196 p = Process(target=f, args=(num, arr))
197 p.start()
198 p.join()
199
Georg Brandl49702152008-09-29 06:43:45 +0000200 print(num.value)
201 print(arr[:])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000202
203 will print ::
204
205 3.1415927
206 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
207
208 The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
209 typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
Georg Brandl2ee470f2008-07-16 12:55:28 +0000210 double precision float and ``'i'`` indicates a signed integer. These shared
Benjamin Petersone711caf2008-06-11 16:44:04 +0000211 objects will be process and thread safe.
212
213 For more flexibility in using shared memory one can use the
214 :mod:`multiprocessing.sharedctypes` module which supports the creation of
215 arbitrary ctypes objects allocated from shared memory.
216
217**Server process**
218
219 A manager object returned by :func:`Manager` controls a server process which
Georg Brandl2ee470f2008-07-16 12:55:28 +0000220 holds Python objects and allows other processes to manipulate them using
Benjamin Petersone711caf2008-06-11 16:44:04 +0000221 proxies.
222
223 A manager returned by :func:`Manager` will support types :class:`list`,
224 :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`,
225 :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
226 :class:`Event`, :class:`Queue`, :class:`Value` and :class:`Array`. For
227 example, ::
228
229 from multiprocessing import Process, Manager
230
231 def f(d, l):
232 d[1] = '1'
233 d['2'] = 2
234 d[0.25] = None
235 l.reverse()
236
237 if __name__ == '__main__':
238 manager = Manager()
239
240 d = manager.dict()
241 l = manager.list(range(10))
242
243 p = Process(target=f, args=(d, l))
244 p.start()
245 p.join()
246
Georg Brandl49702152008-09-29 06:43:45 +0000247 print(d)
248 print(l)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000249
250 will print ::
251
252 {0.25: None, 1: '1', '2': 2}
253 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
254
255 Server process managers are more flexible than using shared memory objects
256 because they can be made to support arbitrary object types. Also, a single
257 manager can be shared by processes on different computers over a network.
258 They are, however, slower than using shared memory.
259
260
261Using a pool of workers
262~~~~~~~~~~~~~~~~~~~~~~~
263
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000264The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
Benjamin Petersone711caf2008-06-11 16:44:04 +0000265processes. It has methods which allows tasks to be offloaded to the worker
266processes in a few different ways.
267
268For example::
269
270 from multiprocessing import Pool
271
272 def f(x):
273 return x*x
274
275 if __name__ == '__main__':
Jesse Noller45239682008-11-28 18:46:19 +0000276 pool = Pool(processes=4) # start 4 worker processes
277 result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
278 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
279 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
Benjamin Petersone711caf2008-06-11 16:44:04 +0000280
281
282Reference
283---------
284
285The :mod:`multiprocessing` package mostly replicates the API of the
286:mod:`threading` module.
287
288
289:class:`Process` and exceptions
290~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
291
292.. class:: Process([group[, target[, name[, args[, kwargs]]]]])
293
294 Process objects represent activity that is run in a separate process. The
295 :class:`Process` class has equivalents of all the methods of
296 :class:`threading.Thread`.
297
298 The constructor should always be called with keyword arguments. *group*
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000299 should always be ``None``; it exists solely for compatibility with
Benjamin Petersona786b022008-08-25 21:05:21 +0000300 :class:`threading.Thread`. *target* is the callable object to be invoked by
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000301 the :meth:`run()` method. It defaults to ``None``, meaning nothing is
Benjamin Petersone711caf2008-06-11 16:44:04 +0000302 called. *name* is the process name. By default, a unique name is constructed
303 of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\
304 :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
305 is determined by the *generation* of the process. *args* is the argument
306 tuple for the target invocation. *kwargs* is a dictionary of keyword
307 arguments for the target invocation. By default, no arguments are passed to
308 *target*.
309
310 If a subclass overrides the constructor, it must make sure it invokes the
311 base class constructor (:meth:`Process.__init__`) before doing anything else
312 to the process.
313
314 .. method:: run()
315
316 Method representing the process's activity.
317
318 You may override this method in a subclass. The standard :meth:`run`
319 method invokes the callable object passed to the object's constructor as
320 the target argument, if any, with sequential and keyword arguments taken
321 from the *args* and *kwargs* arguments, respectively.
322
323 .. method:: start()
324
325 Start the process's activity.
326
327 This must be called at most once per process object. It arranges for the
328 object's :meth:`run` method to be invoked in a separate process.
329
330 .. method:: join([timeout])
331
332 Block the calling thread until the process whose :meth:`join` method is
333 called terminates or until the optional timeout occurs.
334
335 If *timeout* is ``None`` then there is no timeout.
336
337 A process can be joined many times.
338
339 A process cannot join itself because this would cause a deadlock. It is
340 an error to attempt to join a process before it has been started.
341
Benjamin Petersona786b022008-08-25 21:05:21 +0000342 .. attribute:: name
Benjamin Petersone711caf2008-06-11 16:44:04 +0000343
Benjamin Petersona786b022008-08-25 21:05:21 +0000344 The process's name.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000345
346 The name is a string used for identification purposes only. It has no
347 semantics. Multiple processes may be given the same name. The initial
348 name is set by the constructor.
349
Jesse Noller45239682008-11-28 18:46:19 +0000350 .. method:: is_alive
Benjamin Petersone711caf2008-06-11 16:44:04 +0000351
352 Return whether the process is alive.
353
354 Roughly, a process object is alive from the moment the :meth:`start`
355 method returns until the child process terminates.
356
Benjamin Petersona786b022008-08-25 21:05:21 +0000357 .. attribute:: daemon
Benjamin Petersone711caf2008-06-11 16:44:04 +0000358
Benjamin Petersonda10d3b2009-01-01 00:23:30 +0000359 The process's daemon flag, a Boolean value. This must be set before
Benjamin Petersona786b022008-08-25 21:05:21 +0000360 :meth:`start` is called.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000361
362 The initial value is inherited from the creating process.
363
364 When a process exits, it attempts to terminate all of its daemonic child
365 processes.
366
367 Note that a daemonic process is not allowed to create child processes.
368 Otherwise a daemonic process would leave its children orphaned if it gets
369 terminated when its parent process exits.
370
Benjamin Petersona786b022008-08-25 21:05:21 +0000371 In addition to the :class:`Threading.Thread` API, :class:`Process` objects
372 also support the following attributes and methods:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000373
Benjamin Petersona786b022008-08-25 21:05:21 +0000374 .. attribute:: pid
Benjamin Petersone711caf2008-06-11 16:44:04 +0000375
376 Return the process ID. Before the process is spawned, this will be
377 ``None``.
378
Benjamin Petersona786b022008-08-25 21:05:21 +0000379 .. attribute:: exitcode
Benjamin Petersone711caf2008-06-11 16:44:04 +0000380
Benjamin Petersona786b022008-08-25 21:05:21 +0000381 The child's exit code. This will be ``None`` if the process has not yet
382 terminated. A negative value *-N* indicates that the child was terminated
383 by signal *N*.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000384
Benjamin Petersona786b022008-08-25 21:05:21 +0000385 .. attribute:: authkey
Benjamin Petersone711caf2008-06-11 16:44:04 +0000386
Benjamin Petersona786b022008-08-25 21:05:21 +0000387 The process's authentication key (a byte string).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000388
389 When :mod:`multiprocessing` is initialized the main process is assigned a
390 random string using :func:`os.random`.
391
392 When a :class:`Process` object is created, it will inherit the
Benjamin Petersona786b022008-08-25 21:05:21 +0000393 authentication key of its parent process, although this may be changed by
394 setting :attr:`authkey` to another byte string.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000395
396 See :ref:`multiprocessing-auth-keys`.
397
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000398 .. method:: terminate()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000399
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000400 Terminate the process. On Unix this is done using the ``SIGTERM`` signal;
401 on Windows :cfunc:`TerminateProcess` is used. Note that exit handlers and
402 finally clauses, etc., will not be executed.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000403
404 Note that descendant processes of the process will *not* be terminated --
405 they will simply become orphaned.
406
407 .. warning::
408
409 If this method is used when the associated process is using a pipe or
410 queue then the pipe or queue is liable to become corrupted and may
411 become unusable by other process. Similarly, if the process has
412 acquired a lock or semaphore etc. then terminating it is liable to
413 cause other processes to deadlock.
414
415 Note that the :meth:`start`, :meth:`join`, :meth:`is_alive` and
Benjamin Petersona786b022008-08-25 21:05:21 +0000416 :attr:`exit_code` methods should only be called by the process that created
417 the process object.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000418
419 Example usage of some of the methods of :class:`Process`::
420
Benjamin Peterson206e3072008-10-19 14:07:49 +0000421 >>> import multiprocessing, time, signal
422 >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
Georg Brandl49702152008-09-29 06:43:45 +0000423 >>> print(p, p.is_alive())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000424 <Process(Process-1, initial)> False
425 >>> p.start()
Georg Brandl49702152008-09-29 06:43:45 +0000426 >>> print(p, p.is_alive())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000427 <Process(Process-1, started)> True
428 >>> p.terminate()
Georg Brandl49702152008-09-29 06:43:45 +0000429 >>> print(p, p.is_alive())
Benjamin Petersone711caf2008-06-11 16:44:04 +0000430 <Process(Process-1, stopped[SIGTERM])> False
Benjamin Petersona786b022008-08-25 21:05:21 +0000431 >>> p.exitcode == -signal.SIGTERM
Benjamin Petersone711caf2008-06-11 16:44:04 +0000432 True
433
434
435.. exception:: BufferTooShort
436
437 Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
438 buffer object is too small for the message read.
439
440 If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
441 the message as a byte string.
442
443
444Pipes and Queues
445~~~~~~~~~~~~~~~~
446
447When using multiple processes, one generally uses message passing for
448communication between processes and avoids having to use any synchronization
449primitives like locks.
450
451For passing messages one can use :func:`Pipe` (for a connection between two
452processes) or a queue (which allows multiple producers and consumers).
453
454The :class:`Queue` and :class:`JoinableQueue` types are multi-producer,
Benjamin Peterson257060a2008-06-28 01:42:41 +0000455multi-consumer FIFO queues modelled on the :class:`queue.Queue` class in the
Benjamin Petersone711caf2008-06-11 16:44:04 +0000456standard library. They differ in that :class:`Queue` lacks the
Benjamin Peterson257060a2008-06-28 01:42:41 +0000457:meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join` methods introduced
458into Python 2.5's :class:`queue.Queue` class.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000459
460If you use :class:`JoinableQueue` then you **must** call
461:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
462semaphore used to count the number of unfinished tasks may eventually overflow
463raising an exception.
464
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000465Note that one can also create a shared queue by using a manager object -- see
466:ref:`multiprocessing-managers`.
467
Benjamin Petersone711caf2008-06-11 16:44:04 +0000468.. note::
469
Benjamin Peterson257060a2008-06-28 01:42:41 +0000470 :mod:`multiprocessing` uses the usual :exc:`queue.Empty` and
471 :exc:`queue.Full` exceptions to signal a timeout. They are not available in
Benjamin Petersone711caf2008-06-11 16:44:04 +0000472 the :mod:`multiprocessing` namespace so you need to import them from
Benjamin Peterson257060a2008-06-28 01:42:41 +0000473 :mod:`queue`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000474
475
476.. warning::
477
478 If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
479 while it is trying to use a :class:`Queue`, then the data in the queue is
480 likely to become corrupted. This may cause any other processes to get an
481 exception when it tries to use the queue later on.
482
483.. warning::
484
485 As mentioned above, if a child process has put items on a queue (and it has
486 not used :meth:`JoinableQueue.cancel_join_thread`), then that process will
487 not terminate until all buffered items have been flushed to the pipe.
488
489 This means that if you try joining that process you may get a deadlock unless
490 you are sure that all items which have been put on the queue have been
491 consumed. Similarly, if the child process is non-daemonic then the parent
Georg Brandl2ee470f2008-07-16 12:55:28 +0000492 process may hang on exit when it tries to join all its non-daemonic children.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000493
494 Note that a queue created using a manager does not have this issue. See
495 :ref:`multiprocessing-programming`.
496
Benjamin Petersone711caf2008-06-11 16:44:04 +0000497For an example of the usage of queues for interprocess communication see
498:ref:`multiprocessing-examples`.
499
500
501.. function:: Pipe([duplex])
502
503 Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing
504 the ends of a pipe.
505
506 If *duplex* is ``True`` (the default) then the pipe is bidirectional. If
507 *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
508 used for receiving messages and ``conn2`` can only be used for sending
509 messages.
510
511
512.. class:: Queue([maxsize])
513
514 Returns a process shared queue implemented using a pipe and a few
515 locks/semaphores. When a process first puts an item on the queue a feeder
516 thread is started which transfers objects from a buffer into the pipe.
517
Benjamin Peterson257060a2008-06-28 01:42:41 +0000518 The usual :exc:`queue.Empty` and :exc:`queue.Full` exceptions from the
Benjamin Petersone711caf2008-06-11 16:44:04 +0000519 standard library's :mod:`Queue` module are raised to signal timeouts.
520
Benjamin Peterson257060a2008-06-28 01:42:41 +0000521 :class:`Queue` implements all the methods of :class:`queue.Queue` except for
522 :meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000523
524 .. method:: qsize()
525
526 Return the approximate size of the queue. Because of
527 multithreading/multiprocessing semantics, this number is not reliable.
528
529 Note that this may raise :exc:`NotImplementedError` on Unix platforms like
Georg Brandlc575c902008-09-13 17:46:05 +0000530 Mac OS X where ``sem_getvalue()`` is not implemented.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000531
532 .. method:: empty()
533
534 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
535 multithreading/multiprocessing semantics, this is not reliable.
536
537 .. method:: full()
538
539 Return ``True`` if the queue is full, ``False`` otherwise. Because of
540 multithreading/multiprocessing semantics, this is not reliable.
541
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000542 .. method:: put(item[, block[, timeout]])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000543
Georg Brandl48310cd2009-01-03 21:18:54 +0000544 Put item into the queue. If the optional argument *block* is ``True``
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000545 (the default) and *timeout* is ``None`` (the default), block if necessary until
Benjamin Petersone711caf2008-06-11 16:44:04 +0000546 a free slot is available. If *timeout* is a positive number, it blocks at
Benjamin Peterson257060a2008-06-28 01:42:41 +0000547 most *timeout* seconds and raises the :exc:`queue.Full` exception if no
Benjamin Petersone711caf2008-06-11 16:44:04 +0000548 free slot was available within that time. Otherwise (*block* is
549 ``False``), put an item on the queue if a free slot is immediately
Benjamin Peterson257060a2008-06-28 01:42:41 +0000550 available, else raise the :exc:`queue.Full` exception (*timeout* is
Benjamin Petersone711caf2008-06-11 16:44:04 +0000551 ignored in that case).
552
553 .. method:: put_nowait(item)
554
555 Equivalent to ``put(item, False)``.
556
557 .. method:: get([block[, timeout]])
558
559 Remove and return an item from the queue. If optional args *block* is
560 ``True`` (the default) and *timeout* is ``None`` (the default), block if
561 necessary until an item is available. If *timeout* is a positive number,
Benjamin Peterson257060a2008-06-28 01:42:41 +0000562 it blocks at most *timeout* seconds and raises the :exc:`queue.Empty`
Benjamin Petersone711caf2008-06-11 16:44:04 +0000563 exception if no item was available within that time. Otherwise (block is
564 ``False``), return an item if one is immediately available, else raise the
Benjamin Peterson257060a2008-06-28 01:42:41 +0000565 :exc:`queue.Empty` exception (*timeout* is ignored in that case).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000566
567 .. method:: get_nowait()
568 get_no_wait()
569
570 Equivalent to ``get(False)``.
571
572 :class:`multiprocessing.Queue` has a few additional methods not found in
Georg Brandl2ee470f2008-07-16 12:55:28 +0000573 :class:`queue.Queue`. These methods are usually unnecessary for most
574 code:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000575
576 .. method:: close()
577
578 Indicate that no more data will be put on this queue by the current
579 process. The background thread will quit once it has flushed all buffered
580 data to the pipe. This is called automatically when the queue is garbage
581 collected.
582
583 .. method:: join_thread()
584
585 Join the background thread. This can only be used after :meth:`close` has
586 been called. It blocks until the background thread exits, ensuring that
587 all data in the buffer has been flushed to the pipe.
588
589 By default if a process is not the creator of the queue then on exit it
590 will attempt to join the queue's background thread. The process can call
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000591 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000592
593 .. method:: cancel_join_thread()
594
595 Prevent :meth:`join_thread` from blocking. In particular, this prevents
596 the background thread from being joined automatically when the process
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000597 exits -- see :meth:`join_thread`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000598
599
600.. class:: JoinableQueue([maxsize])
601
602 :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which
603 additionally has :meth:`task_done` and :meth:`join` methods.
604
605 .. method:: task_done()
606
607 Indicate that a formerly enqueued task is complete. Used by queue consumer
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000608 threads. For each :meth:`~Queue.get` used to fetch a task, a subsequent
609 call to :meth:`task_done` tells the queue that the processing on the task
610 is complete.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000611
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000612 If a :meth:`~Queue.join` is currently blocking, it will resume when all
613 items have been processed (meaning that a :meth:`task_done` call was
614 received for every item that had been :meth:`~Queue.put` into the queue).
Benjamin Petersone711caf2008-06-11 16:44:04 +0000615
616 Raises a :exc:`ValueError` if called more times than there were items
617 placed in the queue.
618
619
620 .. method:: join()
621
622 Block until all items in the queue have been gotten and processed.
623
624 The count of unfinished tasks goes up whenever an item is added to the
625 queue. The count goes down whenever a consumer thread calls
626 :meth:`task_done` to indicate that the item was retrieved and all work on
627 it is complete. When the count of unfinished tasks drops to zero,
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000628 :meth:`~Queue.join` unblocks.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000629
630
631Miscellaneous
632~~~~~~~~~~~~~
633
634.. function:: active_children()
635
636 Return list of all live children of the current process.
637
638 Calling this has the side affect of "joining" any processes which have
639 already finished.
640
641.. function:: cpu_count()
642
643 Return the number of CPUs in the system. May raise
644 :exc:`NotImplementedError`.
645
646.. function:: current_process()
647
648 Return the :class:`Process` object corresponding to the current process.
649
650 An analogue of :func:`threading.current_thread`.
651
652.. function:: freeze_support()
653
654 Add support for when a program which uses :mod:`multiprocessing` has been
655 frozen to produce a Windows executable. (Has been tested with **py2exe**,
656 **PyInstaller** and **cx_Freeze**.)
657
658 One needs to call this function straight after the ``if __name__ ==
659 '__main__'`` line of the main module. For example::
660
661 from multiprocessing import Process, freeze_support
662
663 def f():
Georg Brandl49702152008-09-29 06:43:45 +0000664 print('hello world!')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000665
666 if __name__ == '__main__':
667 freeze_support()
668 Process(target=f).start()
669
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000670 If the ``freeze_support()`` line is missed out then trying to run the frozen
671 executable will raise :exc:`RuntimeError`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000672
673 If the module is being run normally by the Python interpreter then
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000674 :func:`freeze_support` has no effect.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000675
676.. function:: set_executable()
677
678 Sets the path of the python interpreter to use when starting a child process.
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000679 (By default :data:`sys.executable` is used). Embedders will probably need to
680 do some thing like ::
Benjamin Petersone711caf2008-06-11 16:44:04 +0000681
682 setExecutable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
683
684 before they can create child processes. (Windows only)
685
686
687.. note::
688
689 :mod:`multiprocessing` contains no analogues of
690 :func:`threading.active_count`, :func:`threading.enumerate`,
691 :func:`threading.settrace`, :func:`threading.setprofile`,
692 :class:`threading.Timer`, or :class:`threading.local`.
693
694
695Connection Objects
696~~~~~~~~~~~~~~~~~~
697
698Connection objects allow the sending and receiving of picklable objects or
699strings. They can be thought of as message oriented connected sockets.
700
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000701Connection objects usually created using :func:`Pipe` -- see also
Benjamin Petersone711caf2008-06-11 16:44:04 +0000702:ref:`multiprocessing-listeners-clients`.
703
704.. class:: Connection
705
706 .. method:: send(obj)
707
708 Send an object to the other end of the connection which should be read
709 using :meth:`recv`.
710
Benjamin Peterson965ce872009-04-05 21:24:58 +0000711 The object must be picklable. Very large pickles (approximately 32 MB+,
712 though it depends on the OS) may raise a ValueError exception.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000713
714 .. method:: recv()
715
716 Return an object sent from the other end of the connection using
717 :meth:`send`. Raises :exc:`EOFError` if there is nothing left to receive
718 and the other end was closed.
719
720 .. method:: fileno()
721
722 Returns the file descriptor or handle used by the connection.
723
724 .. method:: close()
725
726 Close the connection.
727
728 This is called automatically when the connection is garbage collected.
729
730 .. method:: poll([timeout])
731
732 Return whether there is any data available to be read.
733
734 If *timeout* is not specified then it will return immediately. If
735 *timeout* is a number then this specifies the maximum time in seconds to
736 block. If *timeout* is ``None`` then an infinite timeout is used.
737
738 .. method:: send_bytes(buffer[, offset[, size]])
739
740 Send byte data from an object supporting the buffer interface as a
741 complete message.
742
743 If *offset* is given then data is read from that position in *buffer*. If
Benjamin Peterson965ce872009-04-05 21:24:58 +0000744 *size* is given then that many bytes will be read from buffer. Very large
745 buffers (approximately 32 MB+, though it depends on the OS) may raise a
746 ValueError exception
Benjamin Petersone711caf2008-06-11 16:44:04 +0000747
748 .. method:: recv_bytes([maxlength])
749
750 Return a complete message of byte data sent from the other end of the
751 connection as a string. Raises :exc:`EOFError` if there is nothing left
752 to receive and the other end has closed.
753
754 If *maxlength* is specified and the message is longer than *maxlength*
755 then :exc:`IOError` is raised and the connection will no longer be
756 readable.
757
758 .. method:: recv_bytes_into(buffer[, offset])
759
760 Read into *buffer* a complete message of byte data sent from the other end
761 of the connection and return the number of bytes in the message. Raises
762 :exc:`EOFError` if there is nothing left to receive and the other end was
763 closed.
764
765 *buffer* must be an object satisfying the writable buffer interface. If
766 *offset* is given then the message will be written into the buffer from
767 *that position. Offset must be a non-negative integer less than the
768 *length of *buffer* (in bytes).
769
770 If the buffer is too short then a :exc:`BufferTooShort` exception is
771 raised and the complete message is available as ``e.args[0]`` where ``e``
772 is the exception instance.
773
774
775For example:
776
777 >>> from multiprocessing import Pipe
778 >>> a, b = Pipe()
779 >>> a.send([1, 'hello', None])
780 >>> b.recv()
781 [1, 'hello', None]
782 >>> b.send_bytes('thank you')
783 >>> a.recv_bytes()
784 'thank you'
785 >>> import array
786 >>> arr1 = array.array('i', range(5))
787 >>> arr2 = array.array('i', [0] * 10)
788 >>> a.send_bytes(arr1)
789 >>> count = b.recv_bytes_into(arr2)
790 >>> assert count == len(arr1) * arr1.itemsize
791 >>> arr2
792 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
793
794
795.. warning::
796
797 The :meth:`Connection.recv` method automatically unpickles the data it
798 receives, which can be a security risk unless you can trust the process
799 which sent the message.
800
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000801 Therefore, unless the connection object was produced using :func:`Pipe` you
802 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
803 methods after performing some sort of authentication. See
804 :ref:`multiprocessing-auth-keys`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000805
806.. warning::
807
808 If a process is killed while it is trying to read or write to a pipe then
809 the data in the pipe is likely to become corrupted, because it may become
810 impossible to be sure where the message boundaries lie.
811
812
813Synchronization primitives
814~~~~~~~~~~~~~~~~~~~~~~~~~~
815
816Generally synchronization primitives are not as necessary in a multiprocess
Georg Brandl2ee470f2008-07-16 12:55:28 +0000817program as they are in a multithreaded program. See the documentation for
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000818:mod:`threading` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000819
820Note that one can also create synchronization primitives by using a manager
821object -- see :ref:`multiprocessing-managers`.
822
823.. class:: BoundedSemaphore([value])
824
825 A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`.
826
Georg Brandlc575c902008-09-13 17:46:05 +0000827 (On Mac OS X this is indistinguishable from :class:`Semaphore` because
Benjamin Petersone711caf2008-06-11 16:44:04 +0000828 ``sem_getvalue()`` is not implemented on that platform).
829
830.. class:: Condition([lock])
831
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000832 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000833
834 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
835 object from :mod:`multiprocessing`.
836
837.. class:: Event()
838
839 A clone of :class:`threading.Event`.
Benjamin Peterson965ce872009-04-05 21:24:58 +0000840 This method returns the state of the internal semaphore on exit, so it
841 will always return ``True`` except if a timeout is given and the operation
842 times out.
843
Raymond Hettinger35a88362009-04-09 00:08:24 +0000844 .. versionchanged:: 3.1
Benjamin Peterson965ce872009-04-05 21:24:58 +0000845 Previously, the method always returned ``None``.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000846
847.. class:: Lock()
848
849 A non-recursive lock object: a clone of :class:`threading.Lock`.
850
851.. class:: RLock()
852
853 A recursive lock object: a clone of :class:`threading.RLock`.
854
855.. class:: Semaphore([value])
856
857 A bounded semaphore object: a clone of :class:`threading.Semaphore`.
858
859.. note::
860
Benjamin Peterson5289b2b2008-06-28 00:40:54 +0000861 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Petersone711caf2008-06-11 16:44:04 +0000862 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
863 by the equivalents in :mod:`threading`. The signature is
864 ``acquire(block=True, timeout=None)`` with keyword parameters being
865 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
866 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
867 ignored.
Georg Brandl48310cd2009-01-03 21:18:54 +0000868
Jesse Noller45239682008-11-28 18:46:19 +0000869 Note that on OS/X ``sem_timedwait`` is unsupported, so timeout arguments
870 for these will be ignored.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000871
872.. note::
873
874 If the SIGINT signal generated by Ctrl-C arrives while the main thread is
875 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
876 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
877 or :meth:`Condition.wait` then the call will be immediately interrupted and
878 :exc:`KeyboardInterrupt` will be raised.
879
880 This differs from the behaviour of :mod:`threading` where SIGINT will be
881 ignored while the equivalent blocking calls are in progress.
882
883
884Shared :mod:`ctypes` Objects
885~~~~~~~~~~~~~~~~~~~~~~~~~~~~
886
887It is possible to create shared objects using shared memory which can be
888inherited by child processes.
889
Jesse Nollerb0516a62009-01-18 03:11:38 +0000890.. function:: Value(typecode_or_type, *args[, lock])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000891
892 Return a :mod:`ctypes` object allocated from shared memory. By default the
893 return value is actually a synchronized wrapper for the object.
894
895 *typecode_or_type* determines the type of the returned object: it is either a
896 ctypes type or a one character typecode of the kind used by the :mod:`array`
897 module. *\*args* is passed on to the constructor for the type.
898
899 If *lock* is ``True`` (the default) then a new lock object is created to
900 synchronize access to the value. If *lock* is a :class:`Lock` or
901 :class:`RLock` object then that will be used to synchronize access to the
902 value. If *lock* is ``False`` then access to the returned object will not be
903 automatically protected by a lock, so it will not necessarily be
904 "process-safe".
905
906 Note that *lock* is a keyword-only argument.
907
908.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
909
910 Return a ctypes array allocated from shared memory. By default the return
911 value is actually a synchronized wrapper for the array.
912
913 *typecode_or_type* determines the type of the elements of the returned array:
914 it is either a ctypes type or a one character typecode of the kind used by
915 the :mod:`array` module. If *size_or_initializer* is an integer, then it
916 determines the length of the array, and the array will be initially zeroed.
917 Otherwise, *size_or_initializer* is a sequence which is used to initialize
918 the array and whose length determines the length of the array.
919
920 If *lock* is ``True`` (the default) then a new lock object is created to
921 synchronize access to the value. If *lock* is a :class:`Lock` or
922 :class:`RLock` object then that will be used to synchronize access to the
923 value. If *lock* is ``False`` then access to the returned object will not be
924 automatically protected by a lock, so it will not necessarily be
925 "process-safe".
926
927 Note that *lock* is a keyword only argument.
928
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000929 Note that an array of :data:`ctypes.c_char` has *value* and *raw*
Benjamin Petersone711caf2008-06-11 16:44:04 +0000930 attributes which allow one to use it to store and retrieve strings.
931
932
933The :mod:`multiprocessing.sharedctypes` module
934>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
935
936.. module:: multiprocessing.sharedctypes
937 :synopsis: Allocate ctypes objects from shared memory.
938
939The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
940:mod:`ctypes` objects from shared memory which can be inherited by child
941processes.
942
943.. note::
944
Georg Brandl2ee470f2008-07-16 12:55:28 +0000945 Although it is possible to store a pointer in shared memory remember that
946 this will refer to a location in the address space of a specific process.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000947 However, the pointer is quite likely to be invalid in the context of a second
948 process and trying to dereference the pointer from the second process may
949 cause a crash.
950
951.. function:: RawArray(typecode_or_type, size_or_initializer)
952
953 Return a ctypes array allocated from shared memory.
954
955 *typecode_or_type* determines the type of the elements of the returned array:
956 it is either a ctypes type or a one character typecode of the kind used by
957 the :mod:`array` module. If *size_or_initializer* is an integer then it
958 determines the length of the array, and the array will be initially zeroed.
959 Otherwise *size_or_initializer* is a sequence which is used to initialize the
960 array and whose length determines the length of the array.
961
962 Note that setting and getting an element is potentially non-atomic -- use
963 :func:`Array` instead to make sure that access is automatically synchronized
964 using a lock.
965
966.. function:: RawValue(typecode_or_type, *args)
967
968 Return a ctypes object allocated from shared memory.
969
970 *typecode_or_type* determines the type of the returned object: it is either a
971 ctypes type or a one character typecode of the kind used by the :mod:`array`
Jesse Nollerb0516a62009-01-18 03:11:38 +0000972 module. *\*args* is passed on to the constructor for the type.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000973
974 Note that setting and getting the value is potentially non-atomic -- use
975 :func:`Value` instead to make sure that access is automatically synchronized
976 using a lock.
977
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000978 Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
Benjamin Petersone711caf2008-06-11 16:44:04 +0000979 attributes which allow one to use it to store and retrieve strings -- see
980 documentation for :mod:`ctypes`.
981
Jesse Nollerb0516a62009-01-18 03:11:38 +0000982.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])
Benjamin Petersone711caf2008-06-11 16:44:04 +0000983
984 The same as :func:`RawArray` except that depending on the value of *lock* a
985 process-safe synchronization wrapper may be returned instead of a raw ctypes
986 array.
987
988 If *lock* is ``True`` (the default) then a new lock object is created to
989 synchronize access to the value. If *lock* is a :class:`Lock` or
990 :class:`RLock` object then that will be used to synchronize access to the
991 value. If *lock* is ``False`` then access to the returned object will not be
992 automatically protected by a lock, so it will not necessarily be
993 "process-safe".
994
995 Note that *lock* is a keyword-only argument.
996
997.. function:: Value(typecode_or_type, *args[, lock])
998
999 The same as :func:`RawValue` except that depending on the value of *lock* a
1000 process-safe synchronization wrapper may be returned instead of a raw ctypes
1001 object.
1002
1003 If *lock* is ``True`` (the default) then a new lock object is created to
1004 synchronize access to the value. If *lock* is a :class:`Lock` or
1005 :class:`RLock` object then that will be used to synchronize access to the
1006 value. If *lock* is ``False`` then access to the returned object will not be
1007 automatically protected by a lock, so it will not necessarily be
1008 "process-safe".
1009
1010 Note that *lock* is a keyword-only argument.
1011
1012.. function:: copy(obj)
1013
1014 Return a ctypes object allocated from shared memory which is a copy of the
1015 ctypes object *obj*.
1016
1017.. function:: synchronized(obj[, lock])
1018
1019 Return a process-safe wrapper object for a ctypes object which uses *lock* to
1020 synchronize access. If *lock* is ``None`` (the default) then a
1021 :class:`multiprocessing.RLock` object is created automatically.
1022
1023 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001024 object it wraps: :meth:`get_obj` returns the wrapped object and
1025 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001026
1027 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001028 than accessing the raw ctypes object.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001029
1030
1031The table below compares the syntax for creating shared ctypes objects from
1032shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
1033subclass of :class:`ctypes.Structure`.)
1034
1035==================== ========================== ===========================
1036ctypes sharedctypes using type sharedctypes using typecode
1037==================== ========================== ===========================
1038c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
1039MyStruct(4, 6) RawValue(MyStruct, 4, 6)
1040(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
1041(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
1042==================== ========================== ===========================
1043
1044
1045Below is an example where a number of ctypes objects are modified by a child
1046process::
1047
1048 from multiprocessing import Process, Lock
1049 from multiprocessing.sharedctypes import Value, Array
1050 from ctypes import Structure, c_double
1051
1052 class Point(Structure):
1053 _fields_ = [('x', c_double), ('y', c_double)]
1054
1055 def modify(n, x, s, A):
1056 n.value **= 2
1057 x.value **= 2
1058 s.value = s.value.upper()
1059 for a in A:
1060 a.x **= 2
1061 a.y **= 2
1062
1063 if __name__ == '__main__':
1064 lock = Lock()
1065
1066 n = Value('i', 7)
1067 x = Value(ctypes.c_double, 1.0/3.0, lock=False)
1068 s = Array('c', 'hello world', lock=lock)
1069 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1070
1071 p = Process(target=modify, args=(n, x, s, A))
1072 p.start()
1073 p.join()
1074
Georg Brandl49702152008-09-29 06:43:45 +00001075 print(n.value)
1076 print(x.value)
1077 print(s.value)
1078 print([(a.x, a.y) for a in A])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001079
1080
Georg Brandl49702152008-09-29 06:43:45 +00001081.. highlight:: none
Benjamin Petersone711caf2008-06-11 16:44:04 +00001082
1083The results printed are ::
1084
1085 49
1086 0.1111111111111111
1087 HELLO WORLD
1088 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1089
Georg Brandl49702152008-09-29 06:43:45 +00001090.. highlight:: python
Benjamin Petersone711caf2008-06-11 16:44:04 +00001091
1092
1093.. _multiprocessing-managers:
1094
1095Managers
1096~~~~~~~~
1097
1098Managers provide a way to create data which can be shared between different
1099processes. A manager object controls a server process which manages *shared
1100objects*. Other processes can access the shared objects by using proxies.
1101
1102.. function:: multiprocessing.Manager()
1103
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001104 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1105 can be used for sharing objects between processes. The returned manager
1106 object corresponds to a spawned child process and has methods which will
1107 create shared objects and return corresponding proxies.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001108
1109.. module:: multiprocessing.managers
1110 :synopsis: Share data between process with shared objects.
1111
1112Manager processes will be shutdown as soon as they are garbage collected or
1113their parent process exits. The manager classes are defined in the
1114:mod:`multiprocessing.managers` module:
1115
1116.. class:: BaseManager([address[, authkey]])
1117
1118 Create a BaseManager object.
1119
1120 Once created one should call :meth:`start` or :meth:`serve_forever` to ensure
1121 that the manager object refers to a started manager process.
1122
1123 *address* is the address on which the manager process listens for new
1124 connections. If *address* is ``None`` then an arbitrary one is chosen.
1125
1126 *authkey* is the authentication key which will be used to check the validity
1127 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Petersona786b022008-08-25 21:05:21 +00001128 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Petersone711caf2008-06-11 16:44:04 +00001129 must be a string.
1130
1131 .. method:: start()
1132
1133 Start a subprocess to start the manager.
1134
Georg Brandl2ee470f2008-07-16 12:55:28 +00001135 .. method:: serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001136
1137 Run the server in the current process.
1138
1139 .. method:: from_address(address, authkey)
1140
1141 A class method which creates a manager object referring to a pre-existing
1142 server process which is using the given address and authentication key.
1143
Jesse Noller45239682008-11-28 18:46:19 +00001144 .. method:: get_server()
Georg Brandl48310cd2009-01-03 21:18:54 +00001145
Jesse Noller45239682008-11-28 18:46:19 +00001146 Returns a :class:`Server` object which represents the actual server under
Georg Brandl48310cd2009-01-03 21:18:54 +00001147 the control of the Manager. The :class:`Server` object supports the
Georg Brandl1f01deb2009-01-03 22:47:39 +00001148 :meth:`serve_forever` method:
Georg Brandl48310cd2009-01-03 21:18:54 +00001149
Georg Brandl1f01deb2009-01-03 22:47:39 +00001150 >>> from multiprocessing.managers import BaseManager
1151 >>> m = BaseManager(address=('', 50000), authkey='abc'))
1152 >>> server = m.get_server()
1153 >>> s.serve_forever()
Georg Brandl48310cd2009-01-03 21:18:54 +00001154
Georg Brandl1f01deb2009-01-03 22:47:39 +00001155 :class:`Server` additionally have an :attr:`address` attribute.
Jesse Noller45239682008-11-28 18:46:19 +00001156
1157 .. method:: connect()
Georg Brandl48310cd2009-01-03 21:18:54 +00001158
Georg Brandl1f01deb2009-01-03 22:47:39 +00001159 Connect a local manager object to a remote manager process:
Georg Brandl48310cd2009-01-03 21:18:54 +00001160
Jesse Noller45239682008-11-28 18:46:19 +00001161 >>> from multiprocessing.managers import BaseManager
1162 >>> m = BaseManager(address='127.0.0.1', authkey='abc))
1163 >>> m.connect()
1164
Benjamin Petersone711caf2008-06-11 16:44:04 +00001165 .. method:: shutdown()
1166
1167 Stop the process used by the manager. This is only available if
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001168 :meth:`start` has been used to start the server process.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001169
1170 This can be called multiple times.
1171
1172 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1173
1174 A classmethod which can be used for registering a type or callable with
1175 the manager class.
1176
1177 *typeid* is a "type identifier" which is used to identify a particular
1178 type of shared object. This must be a string.
1179
1180 *callable* is a callable used for creating objects for this type
1181 identifier. If a manager instance will be created using the
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001182 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Petersone711caf2008-06-11 16:44:04 +00001183 ``False`` then this can be left as ``None``.
1184
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001185 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1186 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1187 class is created automatically.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001188
1189 *exposed* is used to specify a sequence of method names which proxies for
1190 this typeid should be allowed to access using
1191 :meth:`BaseProxy._callMethod`. (If *exposed* is ``None`` then
1192 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1193 where no exposed list is specified, all "public methods" of the shared
1194 object will be accessible. (Here a "public method" means any attribute
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001195 which has a :meth:`__call__` method and whose name does not begin with
Benjamin Petersone711caf2008-06-11 16:44:04 +00001196 ``'_'``.)
1197
1198 *method_to_typeid* is a mapping used to specify the return type of those
1199 exposed methods which should return a proxy. It maps method names to
1200 typeid strings. (If *method_to_typeid* is ``None`` then
1201 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1202 method's name is not a key of this mapping or if the mapping is ``None``
1203 then the object returned by the method will be copied by value.
1204
1205 *create_method* determines whether a method should be created with name
1206 *typeid* which can be used to tell the server process to create a new
1207 shared object and return a proxy for it. By default it is ``True``.
1208
1209 :class:`BaseManager` instances also have one read-only property:
1210
1211 .. attribute:: address
1212
1213 The address used by the manager.
1214
1215
1216.. class:: SyncManager
1217
1218 A subclass of :class:`BaseManager` which can be used for the synchronization
1219 of processes. Objects of this type are returned by
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001220 :func:`multiprocessing.Manager`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001221
1222 It also supports creation of shared lists and dictionaries.
1223
1224 .. method:: BoundedSemaphore([value])
1225
1226 Create a shared :class:`threading.BoundedSemaphore` object and return a
1227 proxy for it.
1228
1229 .. method:: Condition([lock])
1230
1231 Create a shared :class:`threading.Condition` object and return a proxy for
1232 it.
1233
1234 If *lock* is supplied then it should be a proxy for a
1235 :class:`threading.Lock` or :class:`threading.RLock` object.
1236
1237 .. method:: Event()
1238
1239 Create a shared :class:`threading.Event` object and return a proxy for it.
1240
1241 .. method:: Lock()
1242
1243 Create a shared :class:`threading.Lock` object and return a proxy for it.
1244
1245 .. method:: Namespace()
1246
1247 Create a shared :class:`Namespace` object and return a proxy for it.
1248
1249 .. method:: Queue([maxsize])
1250
Benjamin Peterson257060a2008-06-28 01:42:41 +00001251 Create a shared :class:`queue.Queue` object and return a proxy for it.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001252
1253 .. method:: RLock()
1254
1255 Create a shared :class:`threading.RLock` object and return a proxy for it.
1256
1257 .. method:: Semaphore([value])
1258
1259 Create a shared :class:`threading.Semaphore` object and return a proxy for
1260 it.
1261
1262 .. method:: Array(typecode, sequence)
1263
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001264 Create an array and return a proxy for it.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001265
1266 .. method:: Value(typecode, value)
1267
1268 Create an object with a writable ``value`` attribute and return a proxy
1269 for it.
1270
1271 .. method:: dict()
1272 dict(mapping)
1273 dict(sequence)
1274
1275 Create a shared ``dict`` object and return a proxy for it.
1276
1277 .. method:: list()
1278 list(sequence)
1279
1280 Create a shared ``list`` object and return a proxy for it.
1281
1282
1283Namespace objects
1284>>>>>>>>>>>>>>>>>
1285
1286A namespace object has no public methods, but does have writable attributes.
1287Its representation shows the values of its attributes.
1288
1289However, when using a proxy for a namespace object, an attribute beginning with
1290``'_'`` will be an attribute of the proxy and not an attribute of the referent::
1291
1292 >>> manager = multiprocessing.Manager()
1293 >>> Global = manager.Namespace()
1294 >>> Global.x = 10
1295 >>> Global.y = 'hello'
1296 >>> Global._z = 12.3 # this is an attribute of the proxy
Georg Brandl49702152008-09-29 06:43:45 +00001297 >>> print(Global)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001298 Namespace(x=10, y='hello')
1299
1300
1301Customized managers
1302>>>>>>>>>>>>>>>>>>>
1303
1304To create one's own manager, one creates a subclass of :class:`BaseManager` and
Georg Brandl1f01deb2009-01-03 22:47:39 +00001305use the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001306callables with the manager class. For example::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001307
1308 from multiprocessing.managers import BaseManager
1309
1310 class MathsClass(object):
1311 def add(self, x, y):
1312 return x + y
1313 def mul(self, x, y):
1314 return x * y
1315
1316 class MyManager(BaseManager):
1317 pass
1318
1319 MyManager.register('Maths', MathsClass)
1320
1321 if __name__ == '__main__':
1322 manager = MyManager()
1323 manager.start()
1324 maths = manager.Maths()
Georg Brandl49702152008-09-29 06:43:45 +00001325 print(maths.add(4, 3)) # prints 7
1326 print(maths.mul(7, 8)) # prints 56
Benjamin Petersone711caf2008-06-11 16:44:04 +00001327
1328
1329Using a remote manager
1330>>>>>>>>>>>>>>>>>>>>>>
1331
1332It is possible to run a manager server on one machine and have clients use it
1333from other machines (assuming that the firewalls involved allow it).
1334
1335Running the following commands creates a server for a single shared queue which
1336remote clients can access::
1337
1338 >>> from multiprocessing.managers import BaseManager
Benjamin Peterson257060a2008-06-28 01:42:41 +00001339 >>> import queue
1340 >>> queue = queue.Queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001341 >>> class QueueManager(BaseManager): pass
1342 ...
Jesse Noller45239682008-11-28 18:46:19 +00001343 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001344 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Noller45239682008-11-28 18:46:19 +00001345 >>> s = m.get_server()
1346 >>> s.serveForever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001347
1348One client can access the server as follows::
1349
1350 >>> from multiprocessing.managers import BaseManager
1351 >>> class QueueManager(BaseManager): pass
1352 ...
Jesse Noller45239682008-11-28 18:46:19 +00001353 >>> QueueManager.register('get_queue')
1354 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1355 >>> m.connect()
1356 >>> queue = m.get_queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001357 >>> queue.put('hello')
1358
1359Another client can also use it::
1360
1361 >>> from multiprocessing.managers import BaseManager
1362 >>> class QueueManager(BaseManager): pass
1363 ...
1364 >>> QueueManager.register('getQueue')
1365 >>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='abracadabra')
1366 >>> queue = m.getQueue()
1367 >>> queue.get()
1368 'hello'
1369
Georg Brandl48310cd2009-01-03 21:18:54 +00001370Local processes can also access that queue, using the code from above on the
Jesse Noller45239682008-11-28 18:46:19 +00001371client to access it remotely::
1372
1373 >>> from multiprocessing import Process, Queue
1374 >>> from multiprocessing.managers import BaseManager
1375 >>> class Worker(Process):
1376 ... def __init__(self, q):
1377 ... self.q = q
1378 ... super(Worker, self).__init__()
1379 ... def run(self):
1380 ... self.q.put('local hello')
Georg Brandl48310cd2009-01-03 21:18:54 +00001381 ...
Jesse Noller45239682008-11-28 18:46:19 +00001382 >>> queue = Queue()
1383 >>> w = Worker(queue)
1384 >>> w.start()
1385 >>> class QueueManager(BaseManager): pass
Georg Brandl48310cd2009-01-03 21:18:54 +00001386 ...
Jesse Noller45239682008-11-28 18:46:19 +00001387 >>> QueueManager.register('get_queue', callable=lambda: queue)
1388 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1389 >>> s = m.get_server()
1390 >>> s.serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001391
1392Proxy Objects
1393~~~~~~~~~~~~~
1394
1395A proxy is an object which *refers* to a shared object which lives (presumably)
1396in a different process. The shared object is said to be the *referent* of the
1397proxy. Multiple proxy objects may have the same referent.
1398
1399A proxy object has methods which invoke corresponding methods of its referent
1400(although not every method of the referent will necessarily be available through
1401the proxy). A proxy can usually be used in most of the same ways that its
1402referent can::
1403
1404 >>> from multiprocessing import Manager
1405 >>> manager = Manager()
1406 >>> l = manager.list([i*i for i in range(10)])
Georg Brandl49702152008-09-29 06:43:45 +00001407 >>> print(l)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001408 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Georg Brandl49702152008-09-29 06:43:45 +00001409 >>> print(repr(l))
Benjamin Petersone711caf2008-06-11 16:44:04 +00001410 <ListProxy object, typeid 'list' at 0xb799974c>
1411 >>> l[4]
1412 16
1413 >>> l[2:5]
1414 [4, 9, 16]
1415
1416Notice that applying :func:`str` to a proxy will return the representation of
1417the referent, whereas applying :func:`repr` will return the representation of
1418the proxy.
1419
1420An important feature of proxy objects is that they are picklable so they can be
1421passed between processes. Note, however, that if a proxy is sent to the
1422corresponding manager's process then unpickling it will produce the referent
1423itself. This means, for example, that one shared object can contain a second::
1424
1425 >>> a = manager.list()
1426 >>> b = manager.list()
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001427 >>> a.append(b) # referent of a now contains referent of b
Georg Brandl49702152008-09-29 06:43:45 +00001428 >>> print(a, b)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001429 [[]] []
1430 >>> b.append('hello')
Georg Brandl49702152008-09-29 06:43:45 +00001431 >>> print(a, b)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001432 [['hello']] ['hello']
1433
1434.. note::
1435
1436 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
1437 by value. So, for instance, ::
1438
1439 manager.list([1,2,3]) == [1,2,3]
1440
1441 will return ``False``. One should just use a copy of the referent instead
1442 when making comparisons.
1443
1444.. class:: BaseProxy
1445
1446 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1447
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001448 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001449
1450 Call and return the result of a method of the proxy's referent.
1451
1452 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1453
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001454 proxy._callmethod(methodname, args, kwds)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001455
1456 will evaluate the expression ::
1457
1458 getattr(obj, methodname)(*args, **kwds)
1459
1460 in the manager's process.
1461
1462 The returned value will be a copy of the result of the call or a proxy to
1463 a new shared object -- see documentation for the *method_to_typeid*
1464 argument of :meth:`BaseManager.register`.
1465
1466 If an exception is raised by the call, then then is re-raised by
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001467 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Petersone711caf2008-06-11 16:44:04 +00001468 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001469 raised by :meth:`_callmethod`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001470
1471 Note in particular that an exception will be raised if *methodname* has
1472 not been *exposed*
1473
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001474 An example of the usage of :meth:`_callmethod`::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001475
1476 >>> l = manager.list(range(10))
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001477 >>> l._callmethod('__len__')
Benjamin Petersone711caf2008-06-11 16:44:04 +00001478 10
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001479 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Petersone711caf2008-06-11 16:44:04 +00001480 [2, 3, 4, 5, 6]
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001481 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Petersone711caf2008-06-11 16:44:04 +00001482 Traceback (most recent call last):
1483 ...
1484 IndexError: list index out of range
1485
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001486 .. method:: _getvalue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001487
1488 Return a copy of the referent.
1489
1490 If the referent is unpicklable then this will raise an exception.
1491
1492 .. method:: __repr__
1493
1494 Return a representation of the proxy object.
1495
1496 .. method:: __str__
1497
1498 Return the representation of the referent.
1499
1500
1501Cleanup
1502>>>>>>>
1503
1504A proxy object uses a weakref callback so that when it gets garbage collected it
1505deregisters itself from the manager which owns its referent.
1506
1507A shared object gets deleted from the manager process when there are no longer
1508any proxies referring to it.
1509
1510
1511Process Pools
1512~~~~~~~~~~~~~
1513
1514.. module:: multiprocessing.pool
1515 :synopsis: Create pools of processes.
1516
1517One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001518with the :class:`Pool` class.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001519
1520.. class:: multiprocessing.Pool([processes[, initializer[, initargs]]])
1521
1522 A process pool object which controls a pool of worker processes to which jobs
1523 can be submitted. It supports asynchronous results with timeouts and
1524 callbacks and has a parallel map implementation.
1525
1526 *processes* is the number of worker processes to use. If *processes* is
1527 ``None`` then the number returned by :func:`cpu_count` is used. If
1528 *initializer* is not ``None`` then each worker process will call
1529 ``initializer(*initargs)`` when it starts.
1530
1531 .. method:: apply(func[, args[, kwds]])
1532
Benjamin Peterson37d2fe02008-10-24 22:28:58 +00001533 Call *func* with arguments *args* and keyword arguments *kwds*. It blocks
Jesse Noller7b3c89d2009-01-22 21:56:13 +00001534 till the result is ready. Given this blocks - :meth:`apply_async` is better suited
1535 for performing work in parallel. Additionally, the passed
1536 in function is only executed in one of the workers of the pool.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001537
1538 .. method:: apply_async(func[, args[, kwds[, callback]]])
1539
1540 A variant of the :meth:`apply` method which returns a result object.
1541
1542 If *callback* is specified then it should be a callable which accepts a
1543 single argument. When the result becomes ready *callback* is applied to
1544 it (unless the call failed). *callback* should complete immediately since
1545 otherwise the thread which handles the results will get blocked.
1546
1547 .. method:: map(func, iterable[, chunksize])
1548
Benjamin Petersond23f8222009-04-05 19:13:16 +00001549 A parallel equivalent of the :func:`map` builtin function (it supports only
1550 one *iterable* argument though). It blocks till the result is ready.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001551
1552 This method chops the iterable into a number of chunks which it submits to
1553 the process pool as separate tasks. The (approximate) size of these
1554 chunks can be specified by setting *chunksize* to a positive integer.
1555
1556 .. method:: map_async(func, iterable[, chunksize[, callback]])
1557
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001558 A variant of the :meth:`map` method which returns a result object.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001559
1560 If *callback* is specified then it should be a callable which accepts a
1561 single argument. When the result becomes ready *callback* is applied to
1562 it (unless the call failed). *callback* should complete immediately since
1563 otherwise the thread which handles the results will get blocked.
1564
1565 .. method:: imap(func, iterable[, chunksize])
1566
Georg Brandl92905032008-11-22 08:51:39 +00001567 A lazier version of :meth:`map`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001568
1569 The *chunksize* argument is the same as the one used by the :meth:`.map`
1570 method. For very long iterables using a large value for *chunksize* can
1571 make make the job complete **much** faster than using the default value of
1572 ``1``.
1573
1574 Also if *chunksize* is ``1`` then the :meth:`next` method of the iterator
1575 returned by the :meth:`imap` method has an optional *timeout* parameter:
1576 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1577 result cannot be returned within *timeout* seconds.
1578
1579 .. method:: imap_unordered(func, iterable[, chunksize])
1580
1581 The same as :meth:`imap` except that the ordering of the results from the
1582 returned iterator should be considered arbitrary. (Only when there is
1583 only one worker process is the order guaranteed to be "correct".)
1584
1585 .. method:: close()
1586
1587 Prevents any more tasks from being submitted to the pool. Once all the
1588 tasks have been completed the worker processes will exit.
1589
1590 .. method:: terminate()
1591
1592 Stops the worker processes immediately without completing outstanding
1593 work. When the pool object is garbage collected :meth:`terminate` will be
1594 called immediately.
1595
1596 .. method:: join()
1597
1598 Wait for the worker processes to exit. One must call :meth:`close` or
1599 :meth:`terminate` before using :meth:`join`.
1600
1601
1602.. class:: AsyncResult
1603
1604 The class of the result returned by :meth:`Pool.apply_async` and
1605 :meth:`Pool.map_async`.
1606
Georg Brandle3d70ae2008-11-22 08:54:21 +00001607 .. method:: get([timeout])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001608
1609 Return the result when it arrives. If *timeout* is not ``None`` and the
1610 result does not arrive within *timeout* seconds then
1611 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1612 an exception then that exception will be reraised by :meth:`get`.
1613
1614 .. method:: wait([timeout])
1615
1616 Wait until the result is available or until *timeout* seconds pass.
1617
1618 .. method:: ready()
1619
1620 Return whether the call has completed.
1621
1622 .. method:: successful()
1623
1624 Return whether the call completed without raising an exception. Will
1625 raise :exc:`AssertionError` if the result is not ready.
1626
1627The following example demonstrates the use of a pool::
1628
1629 from multiprocessing import Pool
1630
1631 def f(x):
1632 return x*x
1633
1634 if __name__ == '__main__':
1635 pool = Pool(processes=4) # start 4 worker processes
1636
Georg Brandle3d70ae2008-11-22 08:54:21 +00001637 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Georg Brandl49702152008-09-29 06:43:45 +00001638 print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow
Benjamin Petersone711caf2008-06-11 16:44:04 +00001639
Georg Brandl49702152008-09-29 06:43:45 +00001640 print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]"
Benjamin Petersone711caf2008-06-11 16:44:04 +00001641
1642 it = pool.imap(f, range(10))
Georg Brandl49702152008-09-29 06:43:45 +00001643 print(next(it)) # prints "0"
1644 print(next(it)) # prints "1"
1645 print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow
Benjamin Petersone711caf2008-06-11 16:44:04 +00001646
1647 import time
Georg Brandle3d70ae2008-11-22 08:54:21 +00001648 result = pool.apply_async(time.sleep, (10,))
Georg Brandl49702152008-09-29 06:43:45 +00001649 print(result.get(timeout=1)) # raises TimeoutError
Benjamin Petersone711caf2008-06-11 16:44:04 +00001650
1651
1652.. _multiprocessing-listeners-clients:
1653
1654Listeners and Clients
1655~~~~~~~~~~~~~~~~~~~~~
1656
1657.. module:: multiprocessing.connection
1658 :synopsis: API for dealing with sockets.
1659
1660Usually message passing between processes is done using queues or by using
1661:class:`Connection` objects returned by :func:`Pipe`.
1662
1663However, the :mod:`multiprocessing.connection` module allows some extra
1664flexibility. It basically gives a high level message oriented API for dealing
1665with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001666authentication* using the :mod:`hmac` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001667
1668
1669.. function:: deliver_challenge(connection, authkey)
1670
1671 Send a randomly generated message to the other end of the connection and wait
1672 for a reply.
1673
1674 If the reply matches the digest of the message using *authkey* as the key
1675 then a welcome message is sent to the other end of the connection. Otherwise
1676 :exc:`AuthenticationError` is raised.
1677
1678.. function:: answerChallenge(connection, authkey)
1679
1680 Receive a message, calculate the digest of the message using *authkey* as the
1681 key, and then send the digest back.
1682
1683 If a welcome message is not received, then :exc:`AuthenticationError` is
1684 raised.
1685
1686.. function:: Client(address[, family[, authenticate[, authkey]]])
1687
1688 Attempt to set up a connection to the listener which is using address
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001689 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001690
1691 The type of the connection is determined by *family* argument, but this can
1692 generally be omitted since it can usually be inferred from the format of
1693 *address*. (See :ref:`multiprocessing-address-formats`)
1694
1695 If *authentication* is ``True`` or *authkey* is a string then digest
1696 authentication is used. The key used for authentication will be either
Benjamin Petersona786b022008-08-25 21:05:21 +00001697 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001698 If authentication fails then :exc:`AuthenticationError` is raised. See
1699 :ref:`multiprocessing-auth-keys`.
1700
1701.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1702
1703 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1704 connections.
1705
1706 *address* is the address to be used by the bound socket or named pipe of the
1707 listener object.
1708
Benjamin Petersond23f8222009-04-05 19:13:16 +00001709 .. note::
1710
1711 If an address of '0.0.0.0' is used, the address will not be a connectable
1712 end point on Windows. If you require a connectable end-point,
1713 you should use '127.0.0.1'.
1714
Benjamin Petersone711caf2008-06-11 16:44:04 +00001715 *family* is the type of socket (or named pipe) to use. This can be one of
1716 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1717 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1718 the first is guaranteed to be available. If *family* is ``None`` then the
1719 family is inferred from the format of *address*. If *address* is also
1720 ``None`` then a default is chosen. This default is the family which is
1721 assumed to be the fastest available. See
1722 :ref:`multiprocessing-address-formats`. Note that if *family* is
1723 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1724 private temporary directory created using :func:`tempfile.mkstemp`.
1725
1726 If the listener object uses a socket then *backlog* (1 by default) is passed
1727 to the :meth:`listen` method of the socket once it has been bound.
1728
1729 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1730 ``None`` then digest authentication is used.
1731
1732 If *authkey* is a string then it will be used as the authentication key;
1733 otherwise it must be *None*.
1734
1735 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Petersona786b022008-08-25 21:05:21 +00001736 ``current_process().authkey`` is used as the authentication key. If
Benjamin Petersone711caf2008-06-11 16:44:04 +00001737 *authkey* is ``None`` and *authentication* is ``False`` then no
1738 authentication is done. If authentication fails then
1739 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1740
1741 .. method:: accept()
1742
1743 Accept a connection on the bound socket or named pipe of the listener
1744 object and return a :class:`Connection` object. If authentication is
1745 attempted and fails, then :exc:`AuthenticationError` is raised.
1746
1747 .. method:: close()
1748
1749 Close the bound socket or named pipe of the listener object. This is
1750 called automatically when the listener is garbage collected. However it
1751 is advisable to call it explicitly.
1752
1753 Listener objects have the following read-only properties:
1754
1755 .. attribute:: address
1756
1757 The address which is being used by the Listener object.
1758
1759 .. attribute:: last_accepted
1760
1761 The address from which the last accepted connection came. If this is
1762 unavailable then it is ``None``.
1763
1764
1765The module defines two exceptions:
1766
1767.. exception:: AuthenticationError
1768
1769 Exception raised when there is an authentication error.
1770
Benjamin Petersone711caf2008-06-11 16:44:04 +00001771
1772**Examples**
1773
1774The following server code creates a listener which uses ``'secret password'`` as
1775an authentication key. It then waits for a connection and sends some data to
1776the client::
1777
1778 from multiprocessing.connection import Listener
1779 from array import array
1780
1781 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
1782 listener = Listener(address, authkey='secret password')
1783
1784 conn = listener.accept()
Georg Brandl49702152008-09-29 06:43:45 +00001785 print('connection accepted from', listener.last_accepted)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001786
1787 conn.send([2.25, None, 'junk', float])
1788
1789 conn.send_bytes('hello')
1790
1791 conn.send_bytes(array('i', [42, 1729]))
1792
1793 conn.close()
1794 listener.close()
1795
1796The following code connects to the server and receives some data from the
1797server::
1798
1799 from multiprocessing.connection import Client
1800 from array import array
1801
1802 address = ('localhost', 6000)
1803 conn = Client(address, authkey='secret password')
1804
Georg Brandl49702152008-09-29 06:43:45 +00001805 print(conn.recv()) # => [2.25, None, 'junk', float]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001806
Georg Brandl49702152008-09-29 06:43:45 +00001807 print(conn.recv_bytes()) # => 'hello'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001808
1809 arr = array('i', [0, 0, 0, 0, 0])
Georg Brandl49702152008-09-29 06:43:45 +00001810 print(conn.recv_bytes_into(arr)) # => 8
1811 print(arr) # => array('i', [42, 1729, 0, 0, 0])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001812
1813 conn.close()
1814
1815
1816.. _multiprocessing-address-formats:
1817
1818Address Formats
1819>>>>>>>>>>>>>>>
1820
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001821* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Petersone711caf2008-06-11 16:44:04 +00001822 *hostname* is a string and *port* is an integer.
1823
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001824* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Petersone711caf2008-06-11 16:44:04 +00001825 filesystem.
1826
1827* An ``'AF_PIPE'`` address is a string of the form
Benjamin Petersonda10d3b2009-01-01 00:23:30 +00001828 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandl1f01deb2009-01-03 22:47:39 +00001829 pipe on a remote computer called *ServerName* one should use an address of the
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001830 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001831
1832Note that any string beginning with two backslashes is assumed by default to be
1833an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
1834
1835
1836.. _multiprocessing-auth-keys:
1837
1838Authentication keys
1839~~~~~~~~~~~~~~~~~~~
1840
1841When one uses :meth:`Connection.recv`, the data received is automatically
1842unpickled. Unfortunately unpickling data from an untrusted source is a security
1843risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
1844to provide digest authentication.
1845
1846An authentication key is a string which can be thought of as a password: once a
1847connection is established both ends will demand proof that the other knows the
1848authentication key. (Demonstrating that both ends are using the same key does
1849**not** involve sending the key over the connection.)
1850
1851If authentication is requested but do authentication key is specified then the
Benjamin Petersona786b022008-08-25 21:05:21 +00001852return value of ``current_process().authkey`` is used (see
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001853:class:`~multiprocessing.Process`). This value will automatically inherited by
1854any :class:`~multiprocessing.Process` object that the current process creates.
1855This means that (by default) all processes of a multi-process program will share
1856a single authentication key which can be used when setting up connections
Benjamin Petersond23f8222009-04-05 19:13:16 +00001857between themselves.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001858
1859Suitable authentication keys can also be generated by using :func:`os.urandom`.
1860
1861
1862Logging
1863~~~~~~~
1864
1865Some support for logging is available. Note, however, that the :mod:`logging`
1866package does not use process shared locks so it is possible (depending on the
1867handler type) for messages from different processes to get mixed up.
1868
1869.. currentmodule:: multiprocessing
1870.. function:: get_logger()
1871
1872 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
1873 will be created.
1874
Jesse Noller41faa542009-01-25 03:45:53 +00001875 When first created the logger has level :data:`logging.NOTSET` and no
1876 default handler. Messages sent to this logger will not by default propagate
1877 to the root logger.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001878
1879 Note that on Windows child processes will only inherit the level of the
1880 parent process's logger -- any other customization of the logger will not be
1881 inherited.
1882
Jesse Noller41faa542009-01-25 03:45:53 +00001883.. currentmodule:: multiprocessing
1884.. function:: log_to_stderr()
1885
1886 This function performs a call to :func:`get_logger` but in addition to
1887 returning the logger created by get_logger, it adds a handler which sends
1888 output to :data:`sys.stderr` using format
1889 ``'[%(levelname)s/%(processName)s] %(message)s'``.
1890
Benjamin Petersone711caf2008-06-11 16:44:04 +00001891Below is an example session with logging turned on::
1892
Benjamin Peterson206e3072008-10-19 14:07:49 +00001893 >>> import multiprocessing, logging
Jesse Noller41faa542009-01-25 03:45:53 +00001894 >>> logger = multiprocessing.log_to_stderr()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001895 >>> logger.setLevel(logging.INFO)
1896 >>> logger.warning('doomed')
1897 [WARNING/MainProcess] doomed
Benjamin Peterson206e3072008-10-19 14:07:49 +00001898 >>> m = multiprocessing.Manager()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001899 [INFO/SyncManager-1] child process calling self.run()
Jesse Noller41faa542009-01-25 03:45:53 +00001900 [INFO/SyncManager-1] created temp directory /.../pymp-Wh47O_
1901 [INFO/SyncManager-1] manager serving at '/.../listener-lWsERs'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001902 >>> del m
1903 [INFO/MainProcess] sending shutdown message to manager
1904 [INFO/SyncManager-1] manager exiting with exitcode 0
1905
Jesse Noller41faa542009-01-25 03:45:53 +00001906In addition to having these two logging functions, the multiprocessing also
1907exposes two additional logging level attributes. These are :const:`SUBWARNING`
1908and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
1909normal level hierarchy.
1910
1911+----------------+----------------+
1912| Level | Numeric value |
1913+================+================+
1914| ``SUBWARNING`` | 25 |
1915+----------------+----------------+
1916| ``SUBDEBUG`` | 5 |
1917+----------------+----------------+
1918
1919For a full table of logging levels, see the :mod:`logging` module.
1920
1921These additional logging levels are used primarily for certain debug messages
1922within the multiprocessing module. Below is the same example as above, except
1923with :const:`SUBDEBUG` enabled::
1924
1925 >>> import multiprocessing, logging
1926 >>> logger = multiprocessing.log_to_stderr()
1927 >>> logger.setLevel(multiprocessing.SUBDEBUG)
1928 >>> logger.warning('doomed')
1929 [WARNING/MainProcess] doomed
1930 >>> m = multiprocessing.Manager()
1931 [INFO/SyncManager-1] child process calling self.run()
1932 [INFO/SyncManager-1] created temp directory /.../pymp-djGBXN
1933 [INFO/SyncManager-1] manager serving at '/.../pymp-djGBXN/listener-knBYGe'
1934 >>> del m
1935 [SUBDEBUG/MainProcess] finalizer calling ...
1936 [INFO/MainProcess] sending shutdown message to manager
1937 [DEBUG/SyncManager-1] manager received shutdown message
1938 [SUBDEBUG/SyncManager-1] calling <Finalize object, callback=unlink, ...
1939 [SUBDEBUG/SyncManager-1] finalizer calling <built-in function unlink> ...
1940 [SUBDEBUG/SyncManager-1] calling <Finalize object, dead>
1941 [SUBDEBUG/SyncManager-1] finalizer calling <function rmtree at 0x5aa730> ...
1942 [INFO/SyncManager-1] manager exiting with exitcode 0
Benjamin Petersone711caf2008-06-11 16:44:04 +00001943
1944The :mod:`multiprocessing.dummy` module
1945~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1946
1947.. module:: multiprocessing.dummy
1948 :synopsis: Dumb wrapper around threading.
1949
1950:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001951no more than a wrapper around the :mod:`threading` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001952
1953
1954.. _multiprocessing-programming:
1955
1956Programming guidelines
1957----------------------
1958
1959There are certain guidelines and idioms which should be adhered to when using
1960:mod:`multiprocessing`.
1961
1962
1963All platforms
1964~~~~~~~~~~~~~
1965
1966Avoid shared state
1967
1968 As far as possible one should try to avoid shifting large amounts of data
1969 between processes.
1970
1971 It is probably best to stick to using queues or pipes for communication
1972 between processes rather than using the lower level synchronization
1973 primitives from the :mod:`threading` module.
1974
1975Picklability
1976
1977 Ensure that the arguments to the methods of proxies are picklable.
1978
1979Thread safety of proxies
1980
1981 Do not use a proxy object from more than one thread unless you protect it
1982 with a lock.
1983
1984 (There is never a problem with different processes using the *same* proxy.)
1985
1986Joining zombie processes
1987
1988 On Unix when a process finishes but has not been joined it becomes a zombie.
1989 There should never be very many because each time a new process starts (or
1990 :func:`active_children` is called) all completed processes which have not
1991 yet been joined will be joined. Also calling a finished process's
1992 :meth:`Process.is_alive` will join the process. Even so it is probably good
1993 practice to explicitly join all the processes that you start.
1994
1995Better to inherit than pickle/unpickle
1996
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001997 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Petersone711caf2008-06-11 16:44:04 +00001998 that child processes can use them. However, one should generally avoid
1999 sending shared objects to other processes using pipes or queues. Instead
2000 you should arrange the program so that a process which need access to a
2001 shared resource created elsewhere can inherit it from an ancestor process.
2002
2003Avoid terminating processes
2004
2005 Using the :meth:`Process.terminate` method to stop a process is liable to
2006 cause any shared resources (such as locks, semaphores, pipes and queues)
2007 currently being used by the process to become broken or unavailable to other
2008 processes.
2009
2010 Therefore it is probably best to only consider using
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002011 :meth:`Process.terminate` on processes which never use any shared resources.
Benjamin Petersone711caf2008-06-11 16:44:04 +00002012
2013Joining processes that use queues
2014
2015 Bear in mind that a process that has put items in a queue will wait before
2016 terminating until all the buffered items are fed by the "feeder" thread to
2017 the underlying pipe. (The child process can call the
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002018 :meth:`Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Petersone711caf2008-06-11 16:44:04 +00002019
2020 This means that whenever you use a queue you need to make sure that all
2021 items which have been put on the queue will eventually be removed before the
2022 process is joined. Otherwise you cannot be sure that processes which have
2023 put items on the queue will terminate. Remember also that non-daemonic
2024 processes will be automatically be joined.
2025
2026 An example which will deadlock is the following::
2027
2028 from multiprocessing import Process, Queue
2029
2030 def f(q):
2031 q.put('X' * 1000000)
2032
2033 if __name__ == '__main__':
2034 queue = Queue()
2035 p = Process(target=f, args=(queue,))
2036 p.start()
2037 p.join() # this deadlocks
2038 obj = queue.get()
2039
2040 A fix here would be to swap the last two lines round (or simply remove the
2041 ``p.join()`` line).
2042
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002043Explicitly pass resources to child processes
Benjamin Petersone711caf2008-06-11 16:44:04 +00002044
2045 On Unix a child process can make use of a shared resource created in a
2046 parent process using a global resource. However, it is better to pass the
2047 object as an argument to the constructor for the child process.
2048
2049 Apart from making the code (potentially) compatible with Windows this also
2050 ensures that as long as the child process is still alive the object will not
2051 be garbage collected in the parent process. This might be important if some
2052 resource is freed when the object is garbage collected in the parent
2053 process.
2054
2055 So for instance ::
2056
2057 from multiprocessing import Process, Lock
2058
2059 def f():
2060 ... do something using "lock" ...
2061
2062 if __name__ == '__main__':
2063 lock = Lock()
2064 for i in range(10):
2065 Process(target=f).start()
2066
2067 should be rewritten as ::
2068
2069 from multiprocessing import Process, Lock
2070
2071 def f(l):
2072 ... do something using "l" ...
2073
2074 if __name__ == '__main__':
2075 lock = Lock()
2076 for i in range(10):
2077 Process(target=f, args=(lock,)).start()
2078
2079
2080Windows
2081~~~~~~~
2082
2083Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2084
2085More picklability
2086
2087 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2088 means, in particular, that bound or unbound methods cannot be used directly
2089 as the ``target`` argument on Windows --- just define a function and use
2090 that instead.
2091
2092 Also, if you subclass :class:`Process` then make sure that instances will be
2093 picklable when the :meth:`Process.start` method is called.
2094
2095Global variables
2096
2097 Bear in mind that if code run in a child process tries to access a global
2098 variable, then the value it sees (if any) may not be the same as the value
2099 in the parent process at the time that :meth:`Process.start` was called.
2100
2101 However, global variables which are just module level constants cause no
2102 problems.
2103
2104Safe importing of main module
2105
2106 Make sure that the main module can be safely imported by a new Python
2107 interpreter without causing unintended side effects (such a starting a new
2108 process).
2109
2110 For example, under Windows running the following module would fail with a
2111 :exc:`RuntimeError`::
2112
2113 from multiprocessing import Process
2114
2115 def foo():
Georg Brandl49702152008-09-29 06:43:45 +00002116 print('hello')
Benjamin Petersone711caf2008-06-11 16:44:04 +00002117
2118 p = Process(target=foo)
2119 p.start()
2120
2121 Instead one should protect the "entry point" of the program by using ``if
2122 __name__ == '__main__':`` as follows::
2123
2124 from multiprocessing import Process, freeze_support
2125
2126 def foo():
Georg Brandl49702152008-09-29 06:43:45 +00002127 print('hello')
Benjamin Petersone711caf2008-06-11 16:44:04 +00002128
2129 if __name__ == '__main__':
2130 freeze_support()
2131 p = Process(target=foo)
2132 p.start()
2133
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002134 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Petersone711caf2008-06-11 16:44:04 +00002135 normally instead of frozen.)
2136
2137 This allows the newly spawned Python interpreter to safely import the module
2138 and then run the module's ``foo()`` function.
2139
2140 Similar restrictions apply if a pool or manager is created in the main
2141 module.
2142
2143
2144.. _multiprocessing-examples:
2145
2146Examples
2147--------
2148
2149Demonstration of how to create and use customized managers and proxies:
2150
2151.. literalinclude:: ../includes/mp_newtype.py
2152
2153
2154Using :class:`Pool`:
2155
2156.. literalinclude:: ../includes/mp_pool.py
2157
2158
2159Synchronization types like locks, conditions and queues:
2160
2161.. literalinclude:: ../includes/mp_synchronize.py
2162
2163
2164An showing how to use queues to feed tasks to a collection of worker process and
2165collect the results:
2166
2167.. literalinclude:: ../includes/mp_workers.py
2168
2169
2170An example of how a pool of worker processes can each run a
2171:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2172socket.
2173
2174.. literalinclude:: ../includes/mp_webserver.py
2175
2176
2177Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2178
2179.. literalinclude:: ../includes/mp_benchmarks.py
2180
2181An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process`
Georg Brandl48310cd2009-01-03 21:18:54 +00002182and others to build a system which can distribute processes and work via a
Benjamin Petersone711caf2008-06-11 16:44:04 +00002183distributed queue to a "cluster" of machines on a network, accessible via SSH.
2184You will need to have private key authentication for all hosts configured for
2185this to work.
2186
Benjamin Peterson95a939c2008-06-14 02:23:29 +00002187.. literalinclude:: ../includes/mp_distributing.py