blob: b5459044748768fd228df4757b7cb49af5b180c1 [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
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001131 .. method:: start([initializer[, initargs]])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001132
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001133 Start a subprocess to start the manager. If *initializer* is not ``None``
1134 then the subprocess will call ``initializer(*initargs)`` when it starts.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001135
Georg Brandl2ee470f2008-07-16 12:55:28 +00001136 .. method:: serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001137
1138 Run the server in the current process.
1139
1140 .. method:: from_address(address, authkey)
1141
1142 A class method which creates a manager object referring to a pre-existing
1143 server process which is using the given address and authentication key.
1144
Jesse Noller45239682008-11-28 18:46:19 +00001145 .. method:: get_server()
Georg Brandl48310cd2009-01-03 21:18:54 +00001146
Jesse Noller45239682008-11-28 18:46:19 +00001147 Returns a :class:`Server` object which represents the actual server under
Georg Brandl48310cd2009-01-03 21:18:54 +00001148 the control of the Manager. The :class:`Server` object supports the
Georg Brandl1f01deb2009-01-03 22:47:39 +00001149 :meth:`serve_forever` method:
Georg Brandl48310cd2009-01-03 21:18:54 +00001150
Georg Brandl1f01deb2009-01-03 22:47:39 +00001151 >>> from multiprocessing.managers import BaseManager
1152 >>> m = BaseManager(address=('', 50000), authkey='abc'))
1153 >>> server = m.get_server()
1154 >>> s.serve_forever()
Georg Brandl48310cd2009-01-03 21:18:54 +00001155
Georg Brandl1f01deb2009-01-03 22:47:39 +00001156 :class:`Server` additionally have an :attr:`address` attribute.
Jesse Noller45239682008-11-28 18:46:19 +00001157
1158 .. method:: connect()
Georg Brandl48310cd2009-01-03 21:18:54 +00001159
Georg Brandl1f01deb2009-01-03 22:47:39 +00001160 Connect a local manager object to a remote manager process:
Georg Brandl48310cd2009-01-03 21:18:54 +00001161
Jesse Noller45239682008-11-28 18:46:19 +00001162 >>> from multiprocessing.managers import BaseManager
1163 >>> m = BaseManager(address='127.0.0.1', authkey='abc))
1164 >>> m.connect()
1165
Benjamin Petersone711caf2008-06-11 16:44:04 +00001166 .. method:: shutdown()
1167
1168 Stop the process used by the manager. This is only available if
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001169 :meth:`start` has been used to start the server process.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001170
1171 This can be called multiple times.
1172
1173 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1174
1175 A classmethod which can be used for registering a type or callable with
1176 the manager class.
1177
1178 *typeid* is a "type identifier" which is used to identify a particular
1179 type of shared object. This must be a string.
1180
1181 *callable* is a callable used for creating objects for this type
1182 identifier. If a manager instance will be created using the
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001183 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Petersone711caf2008-06-11 16:44:04 +00001184 ``False`` then this can be left as ``None``.
1185
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001186 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1187 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1188 class is created automatically.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001189
1190 *exposed* is used to specify a sequence of method names which proxies for
1191 this typeid should be allowed to access using
1192 :meth:`BaseProxy._callMethod`. (If *exposed* is ``None`` then
1193 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1194 where no exposed list is specified, all "public methods" of the shared
1195 object will be accessible. (Here a "public method" means any attribute
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001196 which has a :meth:`__call__` method and whose name does not begin with
Benjamin Petersone711caf2008-06-11 16:44:04 +00001197 ``'_'``.)
1198
1199 *method_to_typeid* is a mapping used to specify the return type of those
1200 exposed methods which should return a proxy. It maps method names to
1201 typeid strings. (If *method_to_typeid* is ``None`` then
1202 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1203 method's name is not a key of this mapping or if the mapping is ``None``
1204 then the object returned by the method will be copied by value.
1205
1206 *create_method* determines whether a method should be created with name
1207 *typeid* which can be used to tell the server process to create a new
1208 shared object and return a proxy for it. By default it is ``True``.
1209
1210 :class:`BaseManager` instances also have one read-only property:
1211
1212 .. attribute:: address
1213
1214 The address used by the manager.
1215
1216
1217.. class:: SyncManager
1218
1219 A subclass of :class:`BaseManager` which can be used for the synchronization
1220 of processes. Objects of this type are returned by
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001221 :func:`multiprocessing.Manager`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001222
1223 It also supports creation of shared lists and dictionaries.
1224
1225 .. method:: BoundedSemaphore([value])
1226
1227 Create a shared :class:`threading.BoundedSemaphore` object and return a
1228 proxy for it.
1229
1230 .. method:: Condition([lock])
1231
1232 Create a shared :class:`threading.Condition` object and return a proxy for
1233 it.
1234
1235 If *lock* is supplied then it should be a proxy for a
1236 :class:`threading.Lock` or :class:`threading.RLock` object.
1237
1238 .. method:: Event()
1239
1240 Create a shared :class:`threading.Event` object and return a proxy for it.
1241
1242 .. method:: Lock()
1243
1244 Create a shared :class:`threading.Lock` object and return a proxy for it.
1245
1246 .. method:: Namespace()
1247
1248 Create a shared :class:`Namespace` object and return a proxy for it.
1249
1250 .. method:: Queue([maxsize])
1251
Benjamin Peterson257060a2008-06-28 01:42:41 +00001252 Create a shared :class:`queue.Queue` object and return a proxy for it.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001253
1254 .. method:: RLock()
1255
1256 Create a shared :class:`threading.RLock` object and return a proxy for it.
1257
1258 .. method:: Semaphore([value])
1259
1260 Create a shared :class:`threading.Semaphore` object and return a proxy for
1261 it.
1262
1263 .. method:: Array(typecode, sequence)
1264
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001265 Create an array and return a proxy for it.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001266
1267 .. method:: Value(typecode, value)
1268
1269 Create an object with a writable ``value`` attribute and return a proxy
1270 for it.
1271
1272 .. method:: dict()
1273 dict(mapping)
1274 dict(sequence)
1275
1276 Create a shared ``dict`` object and return a proxy for it.
1277
1278 .. method:: list()
1279 list(sequence)
1280
1281 Create a shared ``list`` object and return a proxy for it.
1282
1283
1284Namespace objects
1285>>>>>>>>>>>>>>>>>
1286
1287A namespace object has no public methods, but does have writable attributes.
1288Its representation shows the values of its attributes.
1289
1290However, when using a proxy for a namespace object, an attribute beginning with
1291``'_'`` will be an attribute of the proxy and not an attribute of the referent::
1292
1293 >>> manager = multiprocessing.Manager()
1294 >>> Global = manager.Namespace()
1295 >>> Global.x = 10
1296 >>> Global.y = 'hello'
1297 >>> Global._z = 12.3 # this is an attribute of the proxy
Georg Brandl49702152008-09-29 06:43:45 +00001298 >>> print(Global)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001299 Namespace(x=10, y='hello')
1300
1301
1302Customized managers
1303>>>>>>>>>>>>>>>>>>>
1304
1305To create one's own manager, one creates a subclass of :class:`BaseManager` and
Georg Brandl1f01deb2009-01-03 22:47:39 +00001306use the :meth:`~BaseManager.register` classmethod to register new types or
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001307callables with the manager class. For example::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001308
1309 from multiprocessing.managers import BaseManager
1310
1311 class MathsClass(object):
1312 def add(self, x, y):
1313 return x + y
1314 def mul(self, x, y):
1315 return x * y
1316
1317 class MyManager(BaseManager):
1318 pass
1319
1320 MyManager.register('Maths', MathsClass)
1321
1322 if __name__ == '__main__':
1323 manager = MyManager()
1324 manager.start()
1325 maths = manager.Maths()
Georg Brandl49702152008-09-29 06:43:45 +00001326 print(maths.add(4, 3)) # prints 7
1327 print(maths.mul(7, 8)) # prints 56
Benjamin Petersone711caf2008-06-11 16:44:04 +00001328
1329
1330Using a remote manager
1331>>>>>>>>>>>>>>>>>>>>>>
1332
1333It is possible to run a manager server on one machine and have clients use it
1334from other machines (assuming that the firewalls involved allow it).
1335
1336Running the following commands creates a server for a single shared queue which
1337remote clients can access::
1338
1339 >>> from multiprocessing.managers import BaseManager
Benjamin Peterson257060a2008-06-28 01:42:41 +00001340 >>> import queue
1341 >>> queue = queue.Queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001342 >>> class QueueManager(BaseManager): pass
1343 ...
Jesse Noller45239682008-11-28 18:46:19 +00001344 >>> QueueManager.register('get_queue', callable=lambda:queue)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001345 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
Jesse Noller45239682008-11-28 18:46:19 +00001346 >>> s = m.get_server()
1347 >>> s.serveForever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001348
1349One client can access the server as follows::
1350
1351 >>> from multiprocessing.managers import BaseManager
1352 >>> class QueueManager(BaseManager): pass
1353 ...
Jesse Noller45239682008-11-28 18:46:19 +00001354 >>> QueueManager.register('get_queue')
1355 >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
1356 >>> m.connect()
1357 >>> queue = m.get_queue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001358 >>> queue.put('hello')
1359
1360Another client can also use it::
1361
1362 >>> from multiprocessing.managers import BaseManager
1363 >>> class QueueManager(BaseManager): pass
1364 ...
1365 >>> QueueManager.register('getQueue')
1366 >>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='abracadabra')
1367 >>> queue = m.getQueue()
1368 >>> queue.get()
1369 'hello'
1370
Georg Brandl48310cd2009-01-03 21:18:54 +00001371Local processes can also access that queue, using the code from above on the
Jesse Noller45239682008-11-28 18:46:19 +00001372client to access it remotely::
1373
1374 >>> from multiprocessing import Process, Queue
1375 >>> from multiprocessing.managers import BaseManager
1376 >>> class Worker(Process):
1377 ... def __init__(self, q):
1378 ... self.q = q
1379 ... super(Worker, self).__init__()
1380 ... def run(self):
1381 ... self.q.put('local hello')
Georg Brandl48310cd2009-01-03 21:18:54 +00001382 ...
Jesse Noller45239682008-11-28 18:46:19 +00001383 >>> queue = Queue()
1384 >>> w = Worker(queue)
1385 >>> w.start()
1386 >>> class QueueManager(BaseManager): pass
Georg Brandl48310cd2009-01-03 21:18:54 +00001387 ...
Jesse Noller45239682008-11-28 18:46:19 +00001388 >>> QueueManager.register('get_queue', callable=lambda: queue)
1389 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1390 >>> s = m.get_server()
1391 >>> s.serve_forever()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001392
1393Proxy Objects
1394~~~~~~~~~~~~~
1395
1396A proxy is an object which *refers* to a shared object which lives (presumably)
1397in a different process. The shared object is said to be the *referent* of the
1398proxy. Multiple proxy objects may have the same referent.
1399
1400A proxy object has methods which invoke corresponding methods of its referent
1401(although not every method of the referent will necessarily be available through
1402the proxy). A proxy can usually be used in most of the same ways that its
1403referent can::
1404
1405 >>> from multiprocessing import Manager
1406 >>> manager = Manager()
1407 >>> l = manager.list([i*i for i in range(10)])
Georg Brandl49702152008-09-29 06:43:45 +00001408 >>> print(l)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001409 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Georg Brandl49702152008-09-29 06:43:45 +00001410 >>> print(repr(l))
Benjamin Petersone711caf2008-06-11 16:44:04 +00001411 <ListProxy object, typeid 'list' at 0xb799974c>
1412 >>> l[4]
1413 16
1414 >>> l[2:5]
1415 [4, 9, 16]
1416
1417Notice that applying :func:`str` to a proxy will return the representation of
1418the referent, whereas applying :func:`repr` will return the representation of
1419the proxy.
1420
1421An important feature of proxy objects is that they are picklable so they can be
1422passed between processes. Note, however, that if a proxy is sent to the
1423corresponding manager's process then unpickling it will produce the referent
1424itself. This means, for example, that one shared object can contain a second::
1425
1426 >>> a = manager.list()
1427 >>> b = manager.list()
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001428 >>> a.append(b) # referent of a now contains referent of b
Georg Brandl49702152008-09-29 06:43:45 +00001429 >>> print(a, b)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001430 [[]] []
1431 >>> b.append('hello')
Georg Brandl49702152008-09-29 06:43:45 +00001432 >>> print(a, b)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001433 [['hello']] ['hello']
1434
1435.. note::
1436
1437 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
1438 by value. So, for instance, ::
1439
1440 manager.list([1,2,3]) == [1,2,3]
1441
1442 will return ``False``. One should just use a copy of the referent instead
1443 when making comparisons.
1444
1445.. class:: BaseProxy
1446
1447 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1448
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001449 .. method:: _callmethod(methodname[, args[, kwds]])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001450
1451 Call and return the result of a method of the proxy's referent.
1452
1453 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1454
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001455 proxy._callmethod(methodname, args, kwds)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001456
1457 will evaluate the expression ::
1458
1459 getattr(obj, methodname)(*args, **kwds)
1460
1461 in the manager's process.
1462
1463 The returned value will be a copy of the result of the call or a proxy to
1464 a new shared object -- see documentation for the *method_to_typeid*
1465 argument of :meth:`BaseManager.register`.
1466
1467 If an exception is raised by the call, then then is re-raised by
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001468 :meth:`_callmethod`. If some other exception is raised in the manager's
Benjamin Petersone711caf2008-06-11 16:44:04 +00001469 process then this is converted into a :exc:`RemoteError` exception and is
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001470 raised by :meth:`_callmethod`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001471
1472 Note in particular that an exception will be raised if *methodname* has
1473 not been *exposed*
1474
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001475 An example of the usage of :meth:`_callmethod`::
Benjamin Petersone711caf2008-06-11 16:44:04 +00001476
1477 >>> l = manager.list(range(10))
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001478 >>> l._callmethod('__len__')
Benjamin Petersone711caf2008-06-11 16:44:04 +00001479 10
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001480 >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
Benjamin Petersone711caf2008-06-11 16:44:04 +00001481 [2, 3, 4, 5, 6]
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001482 >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Benjamin Petersone711caf2008-06-11 16:44:04 +00001483 Traceback (most recent call last):
1484 ...
1485 IndexError: list index out of range
1486
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001487 .. method:: _getvalue()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001488
1489 Return a copy of the referent.
1490
1491 If the referent is unpicklable then this will raise an exception.
1492
1493 .. method:: __repr__
1494
1495 Return a representation of the proxy object.
1496
1497 .. method:: __str__
1498
1499 Return the representation of the referent.
1500
1501
1502Cleanup
1503>>>>>>>
1504
1505A proxy object uses a weakref callback so that when it gets garbage collected it
1506deregisters itself from the manager which owns its referent.
1507
1508A shared object gets deleted from the manager process when there are no longer
1509any proxies referring to it.
1510
1511
1512Process Pools
1513~~~~~~~~~~~~~
1514
1515.. module:: multiprocessing.pool
1516 :synopsis: Create pools of processes.
1517
1518One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001519with the :class:`Pool` class.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001520
1521.. class:: multiprocessing.Pool([processes[, initializer[, initargs]]])
1522
1523 A process pool object which controls a pool of worker processes to which jobs
1524 can be submitted. It supports asynchronous results with timeouts and
1525 callbacks and has a parallel map implementation.
1526
1527 *processes* is the number of worker processes to use. If *processes* is
1528 ``None`` then the number returned by :func:`cpu_count` is used. If
1529 *initializer* is not ``None`` then each worker process will call
1530 ``initializer(*initargs)`` when it starts.
1531
1532 .. method:: apply(func[, args[, kwds]])
1533
Benjamin Peterson37d2fe02008-10-24 22:28:58 +00001534 Call *func* with arguments *args* and keyword arguments *kwds*. It blocks
Jesse Noller7b3c89d2009-01-22 21:56:13 +00001535 till the result is ready. Given this blocks - :meth:`apply_async` is better suited
1536 for performing work in parallel. Additionally, the passed
1537 in function is only executed in one of the workers of the pool.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001538
1539 .. method:: apply_async(func[, args[, kwds[, callback]]])
1540
1541 A variant of the :meth:`apply` method which returns a result object.
1542
1543 If *callback* is specified then it should be a callable which accepts a
1544 single argument. When the result becomes ready *callback* is applied to
1545 it (unless the call failed). *callback* should complete immediately since
1546 otherwise the thread which handles the results will get blocked.
1547
1548 .. method:: map(func, iterable[, chunksize])
1549
Benjamin Petersond23f8222009-04-05 19:13:16 +00001550 A parallel equivalent of the :func:`map` builtin function (it supports only
1551 one *iterable* argument though). It blocks till the result is ready.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001552
1553 This method chops the iterable into a number of chunks which it submits to
1554 the process pool as separate tasks. The (approximate) size of these
1555 chunks can be specified by setting *chunksize* to a positive integer.
1556
1557 .. method:: map_async(func, iterable[, chunksize[, callback]])
1558
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001559 A variant of the :meth:`map` method which returns a result object.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001560
1561 If *callback* is specified then it should be a callable which accepts a
1562 single argument. When the result becomes ready *callback* is applied to
1563 it (unless the call failed). *callback* should complete immediately since
1564 otherwise the thread which handles the results will get blocked.
1565
1566 .. method:: imap(func, iterable[, chunksize])
1567
Georg Brandl92905032008-11-22 08:51:39 +00001568 A lazier version of :meth:`map`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001569
1570 The *chunksize* argument is the same as the one used by the :meth:`.map`
1571 method. For very long iterables using a large value for *chunksize* can
1572 make make the job complete **much** faster than using the default value of
1573 ``1``.
1574
1575 Also if *chunksize* is ``1`` then the :meth:`next` method of the iterator
1576 returned by the :meth:`imap` method has an optional *timeout* parameter:
1577 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1578 result cannot be returned within *timeout* seconds.
1579
1580 .. method:: imap_unordered(func, iterable[, chunksize])
1581
1582 The same as :meth:`imap` except that the ordering of the results from the
1583 returned iterator should be considered arbitrary. (Only when there is
1584 only one worker process is the order guaranteed to be "correct".)
1585
1586 .. method:: close()
1587
1588 Prevents any more tasks from being submitted to the pool. Once all the
1589 tasks have been completed the worker processes will exit.
1590
1591 .. method:: terminate()
1592
1593 Stops the worker processes immediately without completing outstanding
1594 work. When the pool object is garbage collected :meth:`terminate` will be
1595 called immediately.
1596
1597 .. method:: join()
1598
1599 Wait for the worker processes to exit. One must call :meth:`close` or
1600 :meth:`terminate` before using :meth:`join`.
1601
1602
1603.. class:: AsyncResult
1604
1605 The class of the result returned by :meth:`Pool.apply_async` and
1606 :meth:`Pool.map_async`.
1607
Georg Brandle3d70ae2008-11-22 08:54:21 +00001608 .. method:: get([timeout])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001609
1610 Return the result when it arrives. If *timeout* is not ``None`` and the
1611 result does not arrive within *timeout* seconds then
1612 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1613 an exception then that exception will be reraised by :meth:`get`.
1614
1615 .. method:: wait([timeout])
1616
1617 Wait until the result is available or until *timeout* seconds pass.
1618
1619 .. method:: ready()
1620
1621 Return whether the call has completed.
1622
1623 .. method:: successful()
1624
1625 Return whether the call completed without raising an exception. Will
1626 raise :exc:`AssertionError` if the result is not ready.
1627
1628The following example demonstrates the use of a pool::
1629
1630 from multiprocessing import Pool
1631
1632 def f(x):
1633 return x*x
1634
1635 if __name__ == '__main__':
1636 pool = Pool(processes=4) # start 4 worker processes
1637
Georg Brandle3d70ae2008-11-22 08:54:21 +00001638 result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously
Georg Brandl49702152008-09-29 06:43:45 +00001639 print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow
Benjamin Petersone711caf2008-06-11 16:44:04 +00001640
Georg Brandl49702152008-09-29 06:43:45 +00001641 print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]"
Benjamin Petersone711caf2008-06-11 16:44:04 +00001642
1643 it = pool.imap(f, range(10))
Georg Brandl49702152008-09-29 06:43:45 +00001644 print(next(it)) # prints "0"
1645 print(next(it)) # prints "1"
1646 print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow
Benjamin Petersone711caf2008-06-11 16:44:04 +00001647
1648 import time
Georg Brandle3d70ae2008-11-22 08:54:21 +00001649 result = pool.apply_async(time.sleep, (10,))
Georg Brandl49702152008-09-29 06:43:45 +00001650 print(result.get(timeout=1)) # raises TimeoutError
Benjamin Petersone711caf2008-06-11 16:44:04 +00001651
1652
1653.. _multiprocessing-listeners-clients:
1654
1655Listeners and Clients
1656~~~~~~~~~~~~~~~~~~~~~
1657
1658.. module:: multiprocessing.connection
1659 :synopsis: API for dealing with sockets.
1660
1661Usually message passing between processes is done using queues or by using
1662:class:`Connection` objects returned by :func:`Pipe`.
1663
1664However, the :mod:`multiprocessing.connection` module allows some extra
1665flexibility. It basically gives a high level message oriented API for dealing
1666with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001667authentication* using the :mod:`hmac` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001668
1669
1670.. function:: deliver_challenge(connection, authkey)
1671
1672 Send a randomly generated message to the other end of the connection and wait
1673 for a reply.
1674
1675 If the reply matches the digest of the message using *authkey* as the key
1676 then a welcome message is sent to the other end of the connection. Otherwise
1677 :exc:`AuthenticationError` is raised.
1678
1679.. function:: answerChallenge(connection, authkey)
1680
1681 Receive a message, calculate the digest of the message using *authkey* as the
1682 key, and then send the digest back.
1683
1684 If a welcome message is not received, then :exc:`AuthenticationError` is
1685 raised.
1686
1687.. function:: Client(address[, family[, authenticate[, authkey]]])
1688
1689 Attempt to set up a connection to the listener which is using address
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001690 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001691
1692 The type of the connection is determined by *family* argument, but this can
1693 generally be omitted since it can usually be inferred from the format of
1694 *address*. (See :ref:`multiprocessing-address-formats`)
1695
1696 If *authentication* is ``True`` or *authkey* is a string then digest
1697 authentication is used. The key used for authentication will be either
Benjamin Petersona786b022008-08-25 21:05:21 +00001698 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001699 If authentication fails then :exc:`AuthenticationError` is raised. See
1700 :ref:`multiprocessing-auth-keys`.
1701
1702.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1703
1704 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1705 connections.
1706
1707 *address* is the address to be used by the bound socket or named pipe of the
1708 listener object.
1709
Benjamin Petersond23f8222009-04-05 19:13:16 +00001710 .. note::
1711
1712 If an address of '0.0.0.0' is used, the address will not be a connectable
1713 end point on Windows. If you require a connectable end-point,
1714 you should use '127.0.0.1'.
1715
Benjamin Petersone711caf2008-06-11 16:44:04 +00001716 *family* is the type of socket (or named pipe) to use. This can be one of
1717 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1718 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1719 the first is guaranteed to be available. If *family* is ``None`` then the
1720 family is inferred from the format of *address*. If *address* is also
1721 ``None`` then a default is chosen. This default is the family which is
1722 assumed to be the fastest available. See
1723 :ref:`multiprocessing-address-formats`. Note that if *family* is
1724 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1725 private temporary directory created using :func:`tempfile.mkstemp`.
1726
1727 If the listener object uses a socket then *backlog* (1 by default) is passed
1728 to the :meth:`listen` method of the socket once it has been bound.
1729
1730 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1731 ``None`` then digest authentication is used.
1732
1733 If *authkey* is a string then it will be used as the authentication key;
1734 otherwise it must be *None*.
1735
1736 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Petersona786b022008-08-25 21:05:21 +00001737 ``current_process().authkey`` is used as the authentication key. If
Benjamin Petersone711caf2008-06-11 16:44:04 +00001738 *authkey* is ``None`` and *authentication* is ``False`` then no
1739 authentication is done. If authentication fails then
1740 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1741
1742 .. method:: accept()
1743
1744 Accept a connection on the bound socket or named pipe of the listener
1745 object and return a :class:`Connection` object. If authentication is
1746 attempted and fails, then :exc:`AuthenticationError` is raised.
1747
1748 .. method:: close()
1749
1750 Close the bound socket or named pipe of the listener object. This is
1751 called automatically when the listener is garbage collected. However it
1752 is advisable to call it explicitly.
1753
1754 Listener objects have the following read-only properties:
1755
1756 .. attribute:: address
1757
1758 The address which is being used by the Listener object.
1759
1760 .. attribute:: last_accepted
1761
1762 The address from which the last accepted connection came. If this is
1763 unavailable then it is ``None``.
1764
1765
1766The module defines two exceptions:
1767
1768.. exception:: AuthenticationError
1769
1770 Exception raised when there is an authentication error.
1771
Benjamin Petersone711caf2008-06-11 16:44:04 +00001772
1773**Examples**
1774
1775The following server code creates a listener which uses ``'secret password'`` as
1776an authentication key. It then waits for a connection and sends some data to
1777the client::
1778
1779 from multiprocessing.connection import Listener
1780 from array import array
1781
1782 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
1783 listener = Listener(address, authkey='secret password')
1784
1785 conn = listener.accept()
Georg Brandl49702152008-09-29 06:43:45 +00001786 print('connection accepted from', listener.last_accepted)
Benjamin Petersone711caf2008-06-11 16:44:04 +00001787
1788 conn.send([2.25, None, 'junk', float])
1789
1790 conn.send_bytes('hello')
1791
1792 conn.send_bytes(array('i', [42, 1729]))
1793
1794 conn.close()
1795 listener.close()
1796
1797The following code connects to the server and receives some data from the
1798server::
1799
1800 from multiprocessing.connection import Client
1801 from array import array
1802
1803 address = ('localhost', 6000)
1804 conn = Client(address, authkey='secret password')
1805
Georg Brandl49702152008-09-29 06:43:45 +00001806 print(conn.recv()) # => [2.25, None, 'junk', float]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001807
Georg Brandl49702152008-09-29 06:43:45 +00001808 print(conn.recv_bytes()) # => 'hello'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001809
1810 arr = array('i', [0, 0, 0, 0, 0])
Georg Brandl49702152008-09-29 06:43:45 +00001811 print(conn.recv_bytes_into(arr)) # => 8
1812 print(arr) # => array('i', [42, 1729, 0, 0, 0])
Benjamin Petersone711caf2008-06-11 16:44:04 +00001813
1814 conn.close()
1815
1816
1817.. _multiprocessing-address-formats:
1818
1819Address Formats
1820>>>>>>>>>>>>>>>
1821
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001822* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Petersone711caf2008-06-11 16:44:04 +00001823 *hostname* is a string and *port* is an integer.
1824
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001825* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Petersone711caf2008-06-11 16:44:04 +00001826 filesystem.
1827
1828* An ``'AF_PIPE'`` address is a string of the form
Benjamin Petersonda10d3b2009-01-01 00:23:30 +00001829 :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
Georg Brandl1f01deb2009-01-03 22:47:39 +00001830 pipe on a remote computer called *ServerName* one should use an address of the
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001831 form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001832
1833Note that any string beginning with two backslashes is assumed by default to be
1834an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
1835
1836
1837.. _multiprocessing-auth-keys:
1838
1839Authentication keys
1840~~~~~~~~~~~~~~~~~~~
1841
1842When one uses :meth:`Connection.recv`, the data received is automatically
1843unpickled. Unfortunately unpickling data from an untrusted source is a security
1844risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
1845to provide digest authentication.
1846
1847An authentication key is a string which can be thought of as a password: once a
1848connection is established both ends will demand proof that the other knows the
1849authentication key. (Demonstrating that both ends are using the same key does
1850**not** involve sending the key over the connection.)
1851
1852If authentication is requested but do authentication key is specified then the
Benjamin Petersona786b022008-08-25 21:05:21 +00001853return value of ``current_process().authkey`` is used (see
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001854:class:`~multiprocessing.Process`). This value will automatically inherited by
1855any :class:`~multiprocessing.Process` object that the current process creates.
1856This means that (by default) all processes of a multi-process program will share
1857a single authentication key which can be used when setting up connections
Benjamin Petersond23f8222009-04-05 19:13:16 +00001858between themselves.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001859
1860Suitable authentication keys can also be generated by using :func:`os.urandom`.
1861
1862
1863Logging
1864~~~~~~~
1865
1866Some support for logging is available. Note, however, that the :mod:`logging`
1867package does not use process shared locks so it is possible (depending on the
1868handler type) for messages from different processes to get mixed up.
1869
1870.. currentmodule:: multiprocessing
1871.. function:: get_logger()
1872
1873 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
1874 will be created.
1875
Jesse Noller41faa542009-01-25 03:45:53 +00001876 When first created the logger has level :data:`logging.NOTSET` and no
1877 default handler. Messages sent to this logger will not by default propagate
1878 to the root logger.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001879
1880 Note that on Windows child processes will only inherit the level of the
1881 parent process's logger -- any other customization of the logger will not be
1882 inherited.
1883
Jesse Noller41faa542009-01-25 03:45:53 +00001884.. currentmodule:: multiprocessing
1885.. function:: log_to_stderr()
1886
1887 This function performs a call to :func:`get_logger` but in addition to
1888 returning the logger created by get_logger, it adds a handler which sends
1889 output to :data:`sys.stderr` using format
1890 ``'[%(levelname)s/%(processName)s] %(message)s'``.
1891
Benjamin Petersone711caf2008-06-11 16:44:04 +00001892Below is an example session with logging turned on::
1893
Benjamin Peterson206e3072008-10-19 14:07:49 +00001894 >>> import multiprocessing, logging
Jesse Noller41faa542009-01-25 03:45:53 +00001895 >>> logger = multiprocessing.log_to_stderr()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001896 >>> logger.setLevel(logging.INFO)
1897 >>> logger.warning('doomed')
1898 [WARNING/MainProcess] doomed
Benjamin Peterson206e3072008-10-19 14:07:49 +00001899 >>> m = multiprocessing.Manager()
Benjamin Petersone711caf2008-06-11 16:44:04 +00001900 [INFO/SyncManager-1] child process calling self.run()
Jesse Noller41faa542009-01-25 03:45:53 +00001901 [INFO/SyncManager-1] created temp directory /.../pymp-Wh47O_
1902 [INFO/SyncManager-1] manager serving at '/.../listener-lWsERs'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001903 >>> del m
1904 [INFO/MainProcess] sending shutdown message to manager
1905 [INFO/SyncManager-1] manager exiting with exitcode 0
1906
Jesse Noller41faa542009-01-25 03:45:53 +00001907In addition to having these two logging functions, the multiprocessing also
1908exposes two additional logging level attributes. These are :const:`SUBWARNING`
1909and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
1910normal level hierarchy.
1911
1912+----------------+----------------+
1913| Level | Numeric value |
1914+================+================+
1915| ``SUBWARNING`` | 25 |
1916+----------------+----------------+
1917| ``SUBDEBUG`` | 5 |
1918+----------------+----------------+
1919
1920For a full table of logging levels, see the :mod:`logging` module.
1921
1922These additional logging levels are used primarily for certain debug messages
1923within the multiprocessing module. Below is the same example as above, except
1924with :const:`SUBDEBUG` enabled::
1925
1926 >>> import multiprocessing, logging
1927 >>> logger = multiprocessing.log_to_stderr()
1928 >>> logger.setLevel(multiprocessing.SUBDEBUG)
1929 >>> logger.warning('doomed')
1930 [WARNING/MainProcess] doomed
1931 >>> m = multiprocessing.Manager()
1932 [INFO/SyncManager-1] child process calling self.run()
1933 [INFO/SyncManager-1] created temp directory /.../pymp-djGBXN
1934 [INFO/SyncManager-1] manager serving at '/.../pymp-djGBXN/listener-knBYGe'
1935 >>> del m
1936 [SUBDEBUG/MainProcess] finalizer calling ...
1937 [INFO/MainProcess] sending shutdown message to manager
1938 [DEBUG/SyncManager-1] manager received shutdown message
1939 [SUBDEBUG/SyncManager-1] calling <Finalize object, callback=unlink, ...
1940 [SUBDEBUG/SyncManager-1] finalizer calling <built-in function unlink> ...
1941 [SUBDEBUG/SyncManager-1] calling <Finalize object, dead>
1942 [SUBDEBUG/SyncManager-1] finalizer calling <function rmtree at 0x5aa730> ...
1943 [INFO/SyncManager-1] manager exiting with exitcode 0
Benjamin Petersone711caf2008-06-11 16:44:04 +00001944
1945The :mod:`multiprocessing.dummy` module
1946~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1947
1948.. module:: multiprocessing.dummy
1949 :synopsis: Dumb wrapper around threading.
1950
1951:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001952no more than a wrapper around the :mod:`threading` module.
Benjamin Petersone711caf2008-06-11 16:44:04 +00001953
1954
1955.. _multiprocessing-programming:
1956
1957Programming guidelines
1958----------------------
1959
1960There are certain guidelines and idioms which should be adhered to when using
1961:mod:`multiprocessing`.
1962
1963
1964All platforms
1965~~~~~~~~~~~~~
1966
1967Avoid shared state
1968
1969 As far as possible one should try to avoid shifting large amounts of data
1970 between processes.
1971
1972 It is probably best to stick to using queues or pipes for communication
1973 between processes rather than using the lower level synchronization
1974 primitives from the :mod:`threading` module.
1975
1976Picklability
1977
1978 Ensure that the arguments to the methods of proxies are picklable.
1979
1980Thread safety of proxies
1981
1982 Do not use a proxy object from more than one thread unless you protect it
1983 with a lock.
1984
1985 (There is never a problem with different processes using the *same* proxy.)
1986
1987Joining zombie processes
1988
1989 On Unix when a process finishes but has not been joined it becomes a zombie.
1990 There should never be very many because each time a new process starts (or
1991 :func:`active_children` is called) all completed processes which have not
1992 yet been joined will be joined. Also calling a finished process's
1993 :meth:`Process.is_alive` will join the process. Even so it is probably good
1994 practice to explicitly join all the processes that you start.
1995
1996Better to inherit than pickle/unpickle
1997
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00001998 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Petersone711caf2008-06-11 16:44:04 +00001999 that child processes can use them. However, one should generally avoid
2000 sending shared objects to other processes using pipes or queues. Instead
2001 you should arrange the program so that a process which need access to a
2002 shared resource created elsewhere can inherit it from an ancestor process.
2003
2004Avoid terminating processes
2005
2006 Using the :meth:`Process.terminate` method to stop a process is liable to
2007 cause any shared resources (such as locks, semaphores, pipes and queues)
2008 currently being used by the process to become broken or unavailable to other
2009 processes.
2010
2011 Therefore it is probably best to only consider using
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002012 :meth:`Process.terminate` on processes which never use any shared resources.
Benjamin Petersone711caf2008-06-11 16:44:04 +00002013
2014Joining processes that use queues
2015
2016 Bear in mind that a process that has put items in a queue will wait before
2017 terminating until all the buffered items are fed by the "feeder" thread to
2018 the underlying pipe. (The child process can call the
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002019 :meth:`Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Petersone711caf2008-06-11 16:44:04 +00002020
2021 This means that whenever you use a queue you need to make sure that all
2022 items which have been put on the queue will eventually be removed before the
2023 process is joined. Otherwise you cannot be sure that processes which have
2024 put items on the queue will terminate. Remember also that non-daemonic
2025 processes will be automatically be joined.
2026
2027 An example which will deadlock is the following::
2028
2029 from multiprocessing import Process, Queue
2030
2031 def f(q):
2032 q.put('X' * 1000000)
2033
2034 if __name__ == '__main__':
2035 queue = Queue()
2036 p = Process(target=f, args=(queue,))
2037 p.start()
2038 p.join() # this deadlocks
2039 obj = queue.get()
2040
2041 A fix here would be to swap the last two lines round (or simply remove the
2042 ``p.join()`` line).
2043
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002044Explicitly pass resources to child processes
Benjamin Petersone711caf2008-06-11 16:44:04 +00002045
2046 On Unix a child process can make use of a shared resource created in a
2047 parent process using a global resource. However, it is better to pass the
2048 object as an argument to the constructor for the child process.
2049
2050 Apart from making the code (potentially) compatible with Windows this also
2051 ensures that as long as the child process is still alive the object will not
2052 be garbage collected in the parent process. This might be important if some
2053 resource is freed when the object is garbage collected in the parent
2054 process.
2055
2056 So for instance ::
2057
2058 from multiprocessing import Process, Lock
2059
2060 def f():
2061 ... do something using "lock" ...
2062
2063 if __name__ == '__main__':
2064 lock = Lock()
2065 for i in range(10):
2066 Process(target=f).start()
2067
2068 should be rewritten as ::
2069
2070 from multiprocessing import Process, Lock
2071
2072 def f(l):
2073 ... do something using "l" ...
2074
2075 if __name__ == '__main__':
2076 lock = Lock()
2077 for i in range(10):
2078 Process(target=f, args=(lock,)).start()
2079
2080
2081Windows
2082~~~~~~~
2083
2084Since Windows lacks :func:`os.fork` it has a few extra restrictions:
2085
2086More picklability
2087
2088 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
2089 means, in particular, that bound or unbound methods cannot be used directly
2090 as the ``target`` argument on Windows --- just define a function and use
2091 that instead.
2092
2093 Also, if you subclass :class:`Process` then make sure that instances will be
2094 picklable when the :meth:`Process.start` method is called.
2095
2096Global variables
2097
2098 Bear in mind that if code run in a child process tries to access a global
2099 variable, then the value it sees (if any) may not be the same as the value
2100 in the parent process at the time that :meth:`Process.start` was called.
2101
2102 However, global variables which are just module level constants cause no
2103 problems.
2104
2105Safe importing of main module
2106
2107 Make sure that the main module can be safely imported by a new Python
2108 interpreter without causing unintended side effects (such a starting a new
2109 process).
2110
2111 For example, under Windows running the following module would fail with a
2112 :exc:`RuntimeError`::
2113
2114 from multiprocessing import Process
2115
2116 def foo():
Georg Brandl49702152008-09-29 06:43:45 +00002117 print('hello')
Benjamin Petersone711caf2008-06-11 16:44:04 +00002118
2119 p = Process(target=foo)
2120 p.start()
2121
2122 Instead one should protect the "entry point" of the program by using ``if
2123 __name__ == '__main__':`` as follows::
2124
2125 from multiprocessing import Process, freeze_support
2126
2127 def foo():
Georg Brandl49702152008-09-29 06:43:45 +00002128 print('hello')
Benjamin Petersone711caf2008-06-11 16:44:04 +00002129
2130 if __name__ == '__main__':
2131 freeze_support()
2132 p = Process(target=foo)
2133 p.start()
2134
Benjamin Peterson5289b2b2008-06-28 00:40:54 +00002135 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Petersone711caf2008-06-11 16:44:04 +00002136 normally instead of frozen.)
2137
2138 This allows the newly spawned Python interpreter to safely import the module
2139 and then run the module's ``foo()`` function.
2140
2141 Similar restrictions apply if a pool or manager is created in the main
2142 module.
2143
2144
2145.. _multiprocessing-examples:
2146
2147Examples
2148--------
2149
2150Demonstration of how to create and use customized managers and proxies:
2151
2152.. literalinclude:: ../includes/mp_newtype.py
2153
2154
2155Using :class:`Pool`:
2156
2157.. literalinclude:: ../includes/mp_pool.py
2158
2159
2160Synchronization types like locks, conditions and queues:
2161
2162.. literalinclude:: ../includes/mp_synchronize.py
2163
2164
2165An showing how to use queues to feed tasks to a collection of worker process and
2166collect the results:
2167
2168.. literalinclude:: ../includes/mp_workers.py
2169
2170
2171An example of how a pool of worker processes can each run a
2172:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2173socket.
2174
2175.. literalinclude:: ../includes/mp_webserver.py
2176
2177
2178Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2179
2180.. literalinclude:: ../includes/mp_benchmarks.py
2181
2182An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process`
Georg Brandl48310cd2009-01-03 21:18:54 +00002183and others to build a system which can distribute processes and work via a
Benjamin Petersone711caf2008-06-11 16:44:04 +00002184distributed queue to a "cluster" of machines on a network, accessible via SSH.
2185You will need to have private key authentication for all hosts configured for
2186this to work.
2187
Benjamin Peterson95a939c2008-06-14 02:23:29 +00002188.. literalinclude:: ../includes/mp_distributing.py