blob: c5901fa57aa99fa33dec5d6a151e220224a5945f [file] [log] [blame]
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001:mod:`multiprocessing` --- Process-based "threading" interface
2==============================================================
3
4.. module:: multiprocessing
5 :synopsis: Process-based "threading" interface.
6
7.. versionadded:: 2.6
8
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00009
Benjamin Peterson190d56e2008-06-11 02:40:25 +000010Introduction
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +000011----------------------
Benjamin Peterson190d56e2008-06-11 02:40:25 +000012
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000013:mod:`multiprocessing` is a package that supports spawning processes using an
14API similar to the :mod:`threading` module. The :mod:`multiprocessing` package
15offers both local and remote concurrency, effectively side-stepping the
16:term:`Global Interpreter Lock` by using subprocesses instead of threads. Due
17to this, the :mod:`multiprocessing` module allows the programmer to fully
18leverage multiple processors on a given machine. It runs on both Unix and
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +000019Windows.
Benjamin Peterson190d56e2008-06-11 02:40:25 +000020
Jesse Noller37040cd2008-09-30 00:15:45 +000021.. warning::
22
Andrew M. Kuchling83b39102008-09-30 12:31:07 +000023 Some of this package's functionality requires a functioning shared semaphore
24 implementation on the host operating system. Without one, the
Jesse Noller37040cd2008-09-30 00:15:45 +000025 :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
Andrew M. Kuchling83b39102008-09-30 12:31:07 +000026 import it will result in an :exc:`ImportError`. See
27 :issue:`3770` for additional information.
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000028
Benjamin Peterson190d56e2008-06-11 02:40:25 +000029The :class:`Process` class
30~~~~~~~~~~~~~~~~~~~~~~~~~~
31
32In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000033object and then calling its :meth:`~Process.start` method. :class:`Process`
Benjamin Peterson190d56e2008-06-11 02:40:25 +000034follows the API of :class:`threading.Thread`. A trivial example of a
35multiprocess program is ::
36
37 from multiprocessing import Process
38
39 def f(name):
40 print 'hello', name
41
42 if __name__ == '__main__':
43 p = Process(target=f, args=('bob',))
44 p.start()
45 p.join()
46
47Here the function ``f`` is run in a child process.
48
49For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is
50necessary, see :ref:`multiprocessing-programming`.
51
52
53
54Exchanging objects between processes
55~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56
57:mod:`multiprocessing` supports two types of communication channel between
58processes:
59
60**Queues**
61
62 The :class:`Queue` class is a near clone of :class:`Queue.Queue`. For
63 example::
64
65 from multiprocessing import Process, Queue
66
67 def f(q):
68 q.put([42, None, 'hello'])
69
70 if __name__ == '__main__':
71 q = Queue()
72 p = Process(target=f, args=(q,))
73 p.start()
74 print q.get() # prints "[42, None, 'hello']"
75 p.join()
76
77 Queues are thread and process safe.
78
79**Pipes**
80
81 The :func:`Pipe` function returns a pair of connection objects connected by a
82 pipe which by default is duplex (two-way). For example::
83
84 from multiprocessing import Process, Pipe
85
86 def f(conn):
87 conn.send([42, None, 'hello'])
88 conn.close()
89
90 if __name__ == '__main__':
91 parent_conn, child_conn = Pipe()
92 p = Process(target=f, args=(child_conn,))
93 p.start()
94 print parent_conn.recv() # prints "[42, None, 'hello']"
95 p.join()
96
97 The two connection objects returned by :func:`Pipe` represent the two ends of
Benjamin Peterson910c2ab2008-06-27 23:22:06 +000098 the pipe. Each connection object has :meth:`~Connection.send` and
99 :meth:`~Connection.recv` methods (among others). Note that data in a pipe
100 may become corrupted if two processes (or threads) try to read from or write
101 to the *same* end of the pipe at the same time. Of course there is no risk
102 of corruption from processes using different ends of the pipe at the same
103 time.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000104
105
106Synchronization between processes
107~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108
109:mod:`multiprocessing` contains equivalents of all the synchronization
110primitives from :mod:`threading`. For instance one can use a lock to ensure
111that only one process prints to standard output at a time::
112
113 from multiprocessing import Process, Lock
114
115 def f(l, i):
116 l.acquire()
117 print 'hello world', i
118 l.release()
119
120 if __name__ == '__main__':
121 lock = Lock()
122
123 for num in range(10):
124 Process(target=f, args=(lock, num)).start()
125
126Without using the lock output from the different processes is liable to get all
127mixed up.
128
129
130Sharing state between processes
131~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
132
133As mentioned above, when doing concurrent programming it is usually best to
134avoid using shared state as far as possible. This is particularly true when
135using multiple processes.
136
137However, if you really do need to use some shared data then
138:mod:`multiprocessing` provides a couple of ways of doing so.
139
140**Shared memory**
141
142 Data can be stored in a shared memory map using :class:`Value` or
143 :class:`Array`. For example, the following code ::
144
145 from multiprocessing import Process, Value, Array
146
147 def f(n, a):
148 n.value = 3.1415927
149 for i in range(len(a)):
150 a[i] = -a[i]
151
152 if __name__ == '__main__':
153 num = Value('d', 0.0)
154 arr = Array('i', range(10))
155
156 p = Process(target=f, args=(num, arr))
157 p.start()
158 p.join()
159
160 print num.value
161 print arr[:]
162
163 will print ::
164
165 3.1415927
166 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
167
168 The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
169 typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
Benjamin Peterson90f36732008-07-12 20:16:19 +0000170 double precision float and ``'i'`` indicates a signed integer. These shared
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000171 objects will be process and thread safe.
172
173 For more flexibility in using shared memory one can use the
174 :mod:`multiprocessing.sharedctypes` module which supports the creation of
175 arbitrary ctypes objects allocated from shared memory.
176
177**Server process**
178
179 A manager object returned by :func:`Manager` controls a server process which
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000180 holds Python objects and allows other processes to manipulate them using
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000181 proxies.
182
183 A manager returned by :func:`Manager` will support types :class:`list`,
184 :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`,
185 :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
186 :class:`Event`, :class:`Queue`, :class:`Value` and :class:`Array`. For
187 example, ::
188
189 from multiprocessing import Process, Manager
190
191 def f(d, l):
192 d[1] = '1'
193 d['2'] = 2
194 d[0.25] = None
195 l.reverse()
196
197 if __name__ == '__main__':
198 manager = Manager()
199
200 d = manager.dict()
201 l = manager.list(range(10))
202
203 p = Process(target=f, args=(d, l))
204 p.start()
205 p.join()
206
207 print d
208 print l
209
210 will print ::
211
212 {0.25: None, 1: '1', '2': 2}
213 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
214
215 Server process managers are more flexible than using shared memory objects
216 because they can be made to support arbitrary object types. Also, a single
217 manager can be shared by processes on different computers over a network.
218 They are, however, slower than using shared memory.
219
220
221Using a pool of workers
222~~~~~~~~~~~~~~~~~~~~~~~
223
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000224The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000225processes. It has methods which allows tasks to be offloaded to the worker
226processes in a few different ways.
227
228For example::
229
230 from multiprocessing import Pool
231
232 def f(x):
233 return x*x
234
235 if __name__ == '__main__':
236 pool = Pool(processes=4) # start 4 worker processes
237 result = pool.applyAsync(f, [10]) # evaluate "f(10)" asynchronously
238 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
239 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
240
241
242Reference
243---------
244
245The :mod:`multiprocessing` package mostly replicates the API of the
246:mod:`threading` module.
247
248
249:class:`Process` and exceptions
250~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251
252.. class:: Process([group[, target[, name[, args[, kwargs]]]]])
253
254 Process objects represent activity that is run in a separate process. The
255 :class:`Process` class has equivalents of all the methods of
256 :class:`threading.Thread`.
257
258 The constructor should always be called with keyword arguments. *group*
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000259 should always be ``None``; it exists solely for compatibility with
Benjamin Peterson73641d72008-08-20 14:07:59 +0000260 :class:`threading.Thread`. *target* is the callable object to be invoked by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000261 the :meth:`run()` method. It defaults to ``None``, meaning nothing is
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000262 called. *name* is the process name. By default, a unique name is constructed
263 of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\
264 :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
265 is determined by the *generation* of the process. *args* is the argument
266 tuple for the target invocation. *kwargs* is a dictionary of keyword
267 arguments for the target invocation. By default, no arguments are passed to
268 *target*.
269
270 If a subclass overrides the constructor, it must make sure it invokes the
271 base class constructor (:meth:`Process.__init__`) before doing anything else
272 to the process.
273
274 .. method:: run()
275
276 Method representing the process's activity.
277
278 You may override this method in a subclass. The standard :meth:`run`
279 method invokes the callable object passed to the object's constructor as
280 the target argument, if any, with sequential and keyword arguments taken
281 from the *args* and *kwargs* arguments, respectively.
282
283 .. method:: start()
284
285 Start the process's activity.
286
287 This must be called at most once per process object. It arranges for the
288 object's :meth:`run` method to be invoked in a separate process.
289
290 .. method:: join([timeout])
291
292 Block the calling thread until the process whose :meth:`join` method is
293 called terminates or until the optional timeout occurs.
294
295 If *timeout* is ``None`` then there is no timeout.
296
297 A process can be joined many times.
298
299 A process cannot join itself because this would cause a deadlock. It is
300 an error to attempt to join a process before it has been started.
301
Benjamin Peterson73641d72008-08-20 14:07:59 +0000302 .. attribute:: name
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000303
Benjamin Peterson73641d72008-08-20 14:07:59 +0000304 The process's name.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000305
306 The name is a string used for identification purposes only. It has no
307 semantics. Multiple processes may be given the same name. The initial
308 name is set by the constructor.
309
310 .. method:: is_alive()
311
312 Return whether the process is alive.
313
314 Roughly, a process object is alive from the moment the :meth:`start`
315 method returns until the child process terminates.
316
Benjamin Peterson73641d72008-08-20 14:07:59 +0000317 .. attribute:: daemon
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000318
Benjamin Peterson73641d72008-08-20 14:07:59 +0000319 The process's daemon flag, a Boolean value. This must be called before
320 :meth:`start` is called.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000321
322 The initial value is inherited from the creating process.
323
324 When a process exits, it attempts to terminate all of its daemonic child
325 processes.
326
327 Note that a daemonic process is not allowed to create child processes.
328 Otherwise a daemonic process would leave its children orphaned if it gets
329 terminated when its parent process exits.
330
Brett Cannon971f1022008-08-24 23:15:19 +0000331 In addition to the :class:`Threading.Thread` API, :class:`Process` objects
332 also support the following attributes and methods:
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000333
Benjamin Peterson73641d72008-08-20 14:07:59 +0000334 .. attribute:: pid
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000335
336 Return the process ID. Before the process is spawned, this will be
337 ``None``.
338
Benjamin Peterson73641d72008-08-20 14:07:59 +0000339 .. attribute:: exitcode
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000340
Benjamin Peterson73641d72008-08-20 14:07:59 +0000341 The child's exit code. This will be ``None`` if the process has not yet
342 terminated. A negative value *-N* indicates that the child was terminated
343 by signal *N*.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000344
Benjamin Peterson73641d72008-08-20 14:07:59 +0000345 .. attribute:: authkey
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000346
Benjamin Peterson73641d72008-08-20 14:07:59 +0000347 The process's authentication key (a byte string).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000348
349 When :mod:`multiprocessing` is initialized the main process is assigned a
350 random string using :func:`os.random`.
351
352 When a :class:`Process` object is created, it will inherit the
Benjamin Peterson73641d72008-08-20 14:07:59 +0000353 authentication key of its parent process, although this may be changed by
354 setting :attr:`authkey` to another byte string.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000355
356 See :ref:`multiprocessing-auth-keys`.
357
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000358 .. method:: terminate()
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000359
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000360 Terminate the process. On Unix this is done using the ``SIGTERM`` signal;
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000361 on Windows :cfunc:`TerminateProcess` is used. Note that exit handlers and
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000362 finally clauses, etc., will not be executed.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000363
364 Note that descendant processes of the process will *not* be terminated --
365 they will simply become orphaned.
366
367 .. warning::
368
369 If this method is used when the associated process is using a pipe or
370 queue then the pipe or queue is liable to become corrupted and may
371 become unusable by other process. Similarly, if the process has
372 acquired a lock or semaphore etc. then terminating it is liable to
373 cause other processes to deadlock.
374
375 Note that the :meth:`start`, :meth:`join`, :meth:`is_alive` and
Benjamin Peterson73641d72008-08-20 14:07:59 +0000376 :attr:`exit_code` methods should only be called by the process that created
377 the process object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000378
379 Example usage of some of the methods of :class:`Process`::
380
381 >>> import processing, time, signal
382 >>> p = processing.Process(target=time.sleep, args=(1000,))
383 >>> print p, p.is_alive()
384 <Process(Process-1, initial)> False
385 >>> p.start()
386 >>> print p, p.is_alive()
387 <Process(Process-1, started)> True
388 >>> p.terminate()
389 >>> print p, p.is_alive()
390 <Process(Process-1, stopped[SIGTERM])> False
Benjamin Peterson73641d72008-08-20 14:07:59 +0000391 >>> p.exitcode == -signal.SIGTERM
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000392 True
393
394
395.. exception:: BufferTooShort
396
397 Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
398 buffer object is too small for the message read.
399
400 If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
401 the message as a byte string.
402
403
404Pipes and Queues
405~~~~~~~~~~~~~~~~
406
407When using multiple processes, one generally uses message passing for
408communication between processes and avoids having to use any synchronization
409primitives like locks.
410
411For passing messages one can use :func:`Pipe` (for a connection between two
412processes) or a queue (which allows multiple producers and consumers).
413
414The :class:`Queue` and :class:`JoinableQueue` types are multi-producer,
415multi-consumer FIFO queues modelled on the :class:`Queue.Queue` class in the
416standard library. They differ in that :class:`Queue` lacks the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000417:meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join` methods introduced
418into Python 2.5's :class:`Queue.Queue` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000419
420If you use :class:`JoinableQueue` then you **must** call
421:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
422semaphore used to count the number of unfinished tasks may eventually overflow
423raising an exception.
424
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000425Note that one can also create a shared queue by using a manager object -- see
426:ref:`multiprocessing-managers`.
427
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000428.. note::
429
430 :mod:`multiprocessing` uses the usual :exc:`Queue.Empty` and
431 :exc:`Queue.Full` exceptions to signal a timeout. They are not available in
432 the :mod:`multiprocessing` namespace so you need to import them from
433 :mod:`Queue`.
434
435
436.. warning::
437
438 If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
439 while it is trying to use a :class:`Queue`, then the data in the queue is
440 likely to become corrupted. This may cause any other processes to get an
441 exception when it tries to use the queue later on.
442
443.. warning::
444
445 As mentioned above, if a child process has put items on a queue (and it has
446 not used :meth:`JoinableQueue.cancel_join_thread`), then that process will
447 not terminate until all buffered items have been flushed to the pipe.
448
449 This means that if you try joining that process you may get a deadlock unless
450 you are sure that all items which have been put on the queue have been
451 consumed. Similarly, if the child process is non-daemonic then the parent
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000452 process may hang on exit when it tries to join all its non-daemonic children.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000453
454 Note that a queue created using a manager does not have this issue. See
455 :ref:`multiprocessing-programming`.
456
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000457For an example of the usage of queues for interprocess communication see
458:ref:`multiprocessing-examples`.
459
460
461.. function:: Pipe([duplex])
462
463 Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing
464 the ends of a pipe.
465
466 If *duplex* is ``True`` (the default) then the pipe is bidirectional. If
467 *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
468 used for receiving messages and ``conn2`` can only be used for sending
469 messages.
470
471
472.. class:: Queue([maxsize])
473
474 Returns a process shared queue implemented using a pipe and a few
475 locks/semaphores. When a process first puts an item on the queue a feeder
476 thread is started which transfers objects from a buffer into the pipe.
477
478 The usual :exc:`Queue.Empty` and :exc:`Queue.Full` exceptions from the
479 standard library's :mod:`Queue` module are raised to signal timeouts.
480
481 :class:`Queue` implements all the methods of :class:`Queue.Queue` except for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000482 :meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000483
484 .. method:: qsize()
485
486 Return the approximate size of the queue. Because of
487 multithreading/multiprocessing semantics, this number is not reliable.
488
489 Note that this may raise :exc:`NotImplementedError` on Unix platforms like
Georg Brandl9af94982008-09-13 17:41:16 +0000490 Mac OS X where ``sem_getvalue()`` is not implemented.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000491
492 .. method:: empty()
493
494 Return ``True`` if the queue is empty, ``False`` otherwise. Because of
495 multithreading/multiprocessing semantics, this is not reliable.
496
497 .. method:: full()
498
499 Return ``True`` if the queue is full, ``False`` otherwise. Because of
500 multithreading/multiprocessing semantics, this is not reliable.
501
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000502 .. method:: put(item[, block[, timeout]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000503
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +0000504 Put item into the queue. If the optional argument *block* is ``True``
505 (the default) and *timeout* is ``None`` (the default), block if necessary until
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000506 a free slot is available. If *timeout* is a positive number, it blocks at
507 most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
508 free slot was available within that time. Otherwise (*block* is
509 ``False``), put an item on the queue if a free slot is immediately
510 available, else raise the :exc:`Queue.Full` exception (*timeout* is
511 ignored in that case).
512
513 .. method:: put_nowait(item)
514
515 Equivalent to ``put(item, False)``.
516
517 .. method:: get([block[, timeout]])
518
519 Remove and return an item from the queue. If optional args *block* is
520 ``True`` (the default) and *timeout* is ``None`` (the default), block if
521 necessary until an item is available. If *timeout* is a positive number,
522 it blocks at most *timeout* seconds and raises the :exc:`Queue.Empty`
523 exception if no item was available within that time. Otherwise (block is
524 ``False``), return an item if one is immediately available, else raise the
525 :exc:`Queue.Empty` exception (*timeout* is ignored in that case).
526
527 .. method:: get_nowait()
528 get_no_wait()
529
530 Equivalent to ``get(False)``.
531
532 :class:`multiprocessing.Queue` has a few additional methods not found in
Andrew M. Kuchlingded01d12008-07-14 00:35:32 +0000533 :class:`Queue.Queue`. These methods are usually unnecessary for most
534 code:
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000535
536 .. method:: close()
537
538 Indicate that no more data will be put on this queue by the current
539 process. The background thread will quit once it has flushed all buffered
540 data to the pipe. This is called automatically when the queue is garbage
541 collected.
542
543 .. method:: join_thread()
544
545 Join the background thread. This can only be used after :meth:`close` has
546 been called. It blocks until the background thread exits, ensuring that
547 all data in the buffer has been flushed to the pipe.
548
549 By default if a process is not the creator of the queue then on exit it
550 will attempt to join the queue's background thread. The process can call
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000551 :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000552
553 .. method:: cancel_join_thread()
554
555 Prevent :meth:`join_thread` from blocking. In particular, this prevents
556 the background thread from being joined automatically when the process
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000557 exits -- see :meth:`join_thread`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000558
559
560.. class:: JoinableQueue([maxsize])
561
562 :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which
563 additionally has :meth:`task_done` and :meth:`join` methods.
564
565 .. method:: task_done()
566
567 Indicate that a formerly enqueued task is complete. Used by queue consumer
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000568 threads. For each :meth:`~Queue.get` used to fetch a task, a subsequent
569 call to :meth:`task_done` tells the queue that the processing on the task
570 is complete.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000571
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000572 If a :meth:`~Queue.join` is currently blocking, it will resume when all
573 items have been processed (meaning that a :meth:`task_done` call was
574 received for every item that had been :meth:`~Queue.put` into the queue).
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000575
576 Raises a :exc:`ValueError` if called more times than there were items
577 placed in the queue.
578
579
580 .. method:: join()
581
582 Block until all items in the queue have been gotten and processed.
583
584 The count of unfinished tasks goes up whenever an item is added to the
585 queue. The count goes down whenever a consumer thread calls
586 :meth:`task_done` to indicate that the item was retrieved and all work on
587 it is complete. When the count of unfinished tasks drops to zero,
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000588 :meth:`~Queue.join` unblocks.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000589
590
591Miscellaneous
592~~~~~~~~~~~~~
593
594.. function:: active_children()
595
596 Return list of all live children of the current process.
597
598 Calling this has the side affect of "joining" any processes which have
599 already finished.
600
601.. function:: cpu_count()
602
603 Return the number of CPUs in the system. May raise
604 :exc:`NotImplementedError`.
605
606.. function:: current_process()
607
608 Return the :class:`Process` object corresponding to the current process.
609
610 An analogue of :func:`threading.current_thread`.
611
612.. function:: freeze_support()
613
614 Add support for when a program which uses :mod:`multiprocessing` has been
615 frozen to produce a Windows executable. (Has been tested with **py2exe**,
616 **PyInstaller** and **cx_Freeze**.)
617
618 One needs to call this function straight after the ``if __name__ ==
619 '__main__'`` line of the main module. For example::
620
621 from multiprocessing import Process, freeze_support
622
623 def f():
624 print 'hello world!'
625
626 if __name__ == '__main__':
627 freeze_support()
628 Process(target=f).start()
629
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000630 If the ``freeze_support()`` line is missed out then trying to run the frozen
631 executable will raise :exc:`RuntimeError`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000632
633 If the module is being run normally by the Python interpreter then
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000634 :func:`freeze_support` has no effect.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000635
636.. function:: set_executable()
637
638 Sets the path of the python interpreter to use when starting a child process.
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000639 (By default :data:`sys.executable` is used). Embedders will probably need to
640 do some thing like ::
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000641
642 setExecutable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
643
644 before they can create child processes. (Windows only)
645
646
647.. note::
648
649 :mod:`multiprocessing` contains no analogues of
650 :func:`threading.active_count`, :func:`threading.enumerate`,
651 :func:`threading.settrace`, :func:`threading.setprofile`,
652 :class:`threading.Timer`, or :class:`threading.local`.
653
654
655Connection Objects
656~~~~~~~~~~~~~~~~~~
657
658Connection objects allow the sending and receiving of picklable objects or
659strings. They can be thought of as message oriented connected sockets.
660
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000661Connection objects usually created using :func:`Pipe` -- see also
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000662:ref:`multiprocessing-listeners-clients`.
663
664.. class:: Connection
665
666 .. method:: send(obj)
667
668 Send an object to the other end of the connection which should be read
669 using :meth:`recv`.
670
671 The object must be picklable.
672
673 .. method:: recv()
674
675 Return an object sent from the other end of the connection using
676 :meth:`send`. Raises :exc:`EOFError` if there is nothing left to receive
677 and the other end was closed.
678
679 .. method:: fileno()
680
681 Returns the file descriptor or handle used by the connection.
682
683 .. method:: close()
684
685 Close the connection.
686
687 This is called automatically when the connection is garbage collected.
688
689 .. method:: poll([timeout])
690
691 Return whether there is any data available to be read.
692
693 If *timeout* is not specified then it will return immediately. If
694 *timeout* is a number then this specifies the maximum time in seconds to
695 block. If *timeout* is ``None`` then an infinite timeout is used.
696
697 .. method:: send_bytes(buffer[, offset[, size]])
698
699 Send byte data from an object supporting the buffer interface as a
700 complete message.
701
702 If *offset* is given then data is read from that position in *buffer*. If
703 *size* is given then that many bytes will be read from buffer.
704
705 .. method:: recv_bytes([maxlength])
706
707 Return a complete message of byte data sent from the other end of the
708 connection as a string. Raises :exc:`EOFError` if there is nothing left
709 to receive and the other end has closed.
710
711 If *maxlength* is specified and the message is longer than *maxlength*
712 then :exc:`IOError` is raised and the connection will no longer be
713 readable.
714
715 .. method:: recv_bytes_into(buffer[, offset])
716
717 Read into *buffer* a complete message of byte data sent from the other end
718 of the connection and return the number of bytes in the message. Raises
719 :exc:`EOFError` if there is nothing left to receive and the other end was
720 closed.
721
722 *buffer* must be an object satisfying the writable buffer interface. If
723 *offset* is given then the message will be written into the buffer from
724 *that position. Offset must be a non-negative integer less than the
725 *length of *buffer* (in bytes).
726
727 If the buffer is too short then a :exc:`BufferTooShort` exception is
728 raised and the complete message is available as ``e.args[0]`` where ``e``
729 is the exception instance.
730
731
732For example:
733
734 >>> from multiprocessing import Pipe
735 >>> a, b = Pipe()
736 >>> a.send([1, 'hello', None])
737 >>> b.recv()
738 [1, 'hello', None]
739 >>> b.send_bytes('thank you')
740 >>> a.recv_bytes()
741 'thank you'
742 >>> import array
743 >>> arr1 = array.array('i', range(5))
744 >>> arr2 = array.array('i', [0] * 10)
745 >>> a.send_bytes(arr1)
746 >>> count = b.recv_bytes_into(arr2)
747 >>> assert count == len(arr1) * arr1.itemsize
748 >>> arr2
749 array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
750
751
752.. warning::
753
754 The :meth:`Connection.recv` method automatically unpickles the data it
755 receives, which can be a security risk unless you can trust the process
756 which sent the message.
757
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000758 Therefore, unless the connection object was produced using :func:`Pipe` you
759 should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
760 methods after performing some sort of authentication. See
761 :ref:`multiprocessing-auth-keys`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000762
763.. warning::
764
765 If a process is killed while it is trying to read or write to a pipe then
766 the data in the pipe is likely to become corrupted, because it may become
767 impossible to be sure where the message boundaries lie.
768
769
770Synchronization primitives
771~~~~~~~~~~~~~~~~~~~~~~~~~~
772
773Generally synchronization primitives are not as necessary in a multiprocess
Andrew M. Kuchling8ea605c2008-07-14 01:18:16 +0000774program as they are in a multithreaded program. See the documentation for
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000775:mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000776
777Note that one can also create synchronization primitives by using a manager
778object -- see :ref:`multiprocessing-managers`.
779
780.. class:: BoundedSemaphore([value])
781
782 A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`.
783
Georg Brandl9af94982008-09-13 17:41:16 +0000784 (On Mac OS X this is indistinguishable from :class:`Semaphore` because
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000785 ``sem_getvalue()`` is not implemented on that platform).
786
787.. class:: Condition([lock])
788
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000789 A condition variable: a clone of :class:`threading.Condition`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000790
791 If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
792 object from :mod:`multiprocessing`.
793
794.. class:: Event()
795
796 A clone of :class:`threading.Event`.
797
798.. class:: Lock()
799
800 A non-recursive lock object: a clone of :class:`threading.Lock`.
801
802.. class:: RLock()
803
804 A recursive lock object: a clone of :class:`threading.RLock`.
805
806.. class:: Semaphore([value])
807
808 A bounded semaphore object: a clone of :class:`threading.Semaphore`.
809
810.. note::
811
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000812 The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000813 :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
814 by the equivalents in :mod:`threading`. The signature is
815 ``acquire(block=True, timeout=None)`` with keyword parameters being
816 acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it
817 specifies a timeout in seconds. If *block* is ``False`` then *timeout* is
818 ignored.
819
820.. note::
821
822 If the SIGINT signal generated by Ctrl-C arrives while the main thread is
823 blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
824 :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
825 or :meth:`Condition.wait` then the call will be immediately interrupted and
826 :exc:`KeyboardInterrupt` will be raised.
827
828 This differs from the behaviour of :mod:`threading` where SIGINT will be
829 ignored while the equivalent blocking calls are in progress.
830
831
832Shared :mod:`ctypes` Objects
833~~~~~~~~~~~~~~~~~~~~~~~~~~~~
834
835It is possible to create shared objects using shared memory which can be
836inherited by child processes.
837
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000838.. function:: Value(typecode_or_type[, *args, lock]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000839
840 Return a :mod:`ctypes` object allocated from shared memory. By default the
841 return value is actually a synchronized wrapper for the object.
842
843 *typecode_or_type* determines the type of the returned object: it is either a
844 ctypes type or a one character typecode of the kind used by the :mod:`array`
845 module. *\*args* is passed on to the constructor for the type.
846
847 If *lock* is ``True`` (the default) then a new lock object is created to
848 synchronize access to the value. If *lock* is a :class:`Lock` or
849 :class:`RLock` object then that will be used to synchronize access to the
850 value. If *lock* is ``False`` then access to the returned object will not be
851 automatically protected by a lock, so it will not necessarily be
852 "process-safe".
853
854 Note that *lock* is a keyword-only argument.
855
856.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)
857
858 Return a ctypes array allocated from shared memory. By default the return
859 value is actually a synchronized wrapper for the array.
860
861 *typecode_or_type* determines the type of the elements of the returned array:
862 it is either a ctypes type or a one character typecode of the kind used by
863 the :mod:`array` module. If *size_or_initializer* is an integer, then it
864 determines the length of the array, and the array will be initially zeroed.
865 Otherwise, *size_or_initializer* is a sequence which is used to initialize
866 the array and whose length determines the length of the array.
867
868 If *lock* is ``True`` (the default) then a new lock object is created to
869 synchronize access to the value. If *lock* is a :class:`Lock` or
870 :class:`RLock` object then that will be used to synchronize access to the
871 value. If *lock* is ``False`` then access to the returned object will not be
872 automatically protected by a lock, so it will not necessarily be
873 "process-safe".
874
875 Note that *lock* is a keyword only argument.
876
877 Note that an array of :data:`ctypes.c_char` has *value* and *rawvalue*
878 attributes which allow one to use it to store and retrieve strings.
879
880
881The :mod:`multiprocessing.sharedctypes` module
882>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
883
884.. module:: multiprocessing.sharedctypes
885 :synopsis: Allocate ctypes objects from shared memory.
886
887The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
888:mod:`ctypes` objects from shared memory which can be inherited by child
889processes.
890
891.. note::
892
Benjamin Peterson90f36732008-07-12 20:16:19 +0000893 Although it is possible to store a pointer in shared memory remember that
894 this will refer to a location in the address space of a specific process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000895 However, the pointer is quite likely to be invalid in the context of a second
896 process and trying to dereference the pointer from the second process may
897 cause a crash.
898
899.. function:: RawArray(typecode_or_type, size_or_initializer)
900
901 Return a ctypes array allocated from shared memory.
902
903 *typecode_or_type* determines the type of the elements of the returned array:
904 it is either a ctypes type or a one character typecode of the kind used by
905 the :mod:`array` module. If *size_or_initializer* is an integer then it
906 determines the length of the array, and the array will be initially zeroed.
907 Otherwise *size_or_initializer* is a sequence which is used to initialize the
908 array and whose length determines the length of the array.
909
910 Note that setting and getting an element is potentially non-atomic -- use
911 :func:`Array` instead to make sure that access is automatically synchronized
912 using a lock.
913
914.. function:: RawValue(typecode_or_type, *args)
915
916 Return a ctypes object allocated from shared memory.
917
918 *typecode_or_type* determines the type of the returned object: it is either a
919 ctypes type or a one character typecode of the kind used by the :mod:`array`
920 module. */*args* is passed on to the constructor for the type.
921
922 Note that setting and getting the value is potentially non-atomic -- use
923 :func:`Value` instead to make sure that access is automatically synchronized
924 using a lock.
925
926 Note that an array of :data:`ctypes.c_char` has ``value`` and ``rawvalue``
927 attributes which allow one to use it to store and retrieve strings -- see
928 documentation for :mod:`ctypes`.
929
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000930.. function:: Array(typecode_or_type, size_or_initializer[, *args[, lock]])
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000931
932 The same as :func:`RawArray` except that depending on the value of *lock* a
933 process-safe synchronization wrapper may be returned instead of a raw ctypes
934 array.
935
936 If *lock* is ``True`` (the default) then a new lock object is created to
937 synchronize access to the value. If *lock* is a :class:`Lock` or
938 :class:`RLock` object then that will be used to synchronize access to the
939 value. If *lock* is ``False`` then access to the returned object will not be
940 automatically protected by a lock, so it will not necessarily be
941 "process-safe".
942
943 Note that *lock* is a keyword-only argument.
944
945.. function:: Value(typecode_or_type, *args[, lock])
946
947 The same as :func:`RawValue` except that depending on the value of *lock* a
948 process-safe synchronization wrapper may be returned instead of a raw ctypes
949 object.
950
951 If *lock* is ``True`` (the default) then a new lock object is created to
952 synchronize access to the value. If *lock* is a :class:`Lock` or
953 :class:`RLock` object then that will be used to synchronize access to the
954 value. If *lock* is ``False`` then access to the returned object will not be
955 automatically protected by a lock, so it will not necessarily be
956 "process-safe".
957
958 Note that *lock* is a keyword-only argument.
959
960.. function:: copy(obj)
961
962 Return a ctypes object allocated from shared memory which is a copy of the
963 ctypes object *obj*.
964
965.. function:: synchronized(obj[, lock])
966
967 Return a process-safe wrapper object for a ctypes object which uses *lock* to
968 synchronize access. If *lock* is ``None`` (the default) then a
969 :class:`multiprocessing.RLock` object is created automatically.
970
971 A synchronized wrapper will have two methods in addition to those of the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000972 object it wraps: :meth:`get_obj` returns the wrapped object and
973 :meth:`get_lock` returns the lock object used for synchronization.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000974
975 Note that accessing the ctypes object through the wrapper can be a lot slower
Benjamin Peterson910c2ab2008-06-27 23:22:06 +0000976 than accessing the raw ctypes object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +0000977
978
979The table below compares the syntax for creating shared ctypes objects from
980shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some
981subclass of :class:`ctypes.Structure`.)
982
983==================== ========================== ===========================
984ctypes sharedctypes using type sharedctypes using typecode
985==================== ========================== ===========================
986c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4)
987MyStruct(4, 6) RawValue(MyStruct, 4, 6)
988(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7)
989(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
990==================== ========================== ===========================
991
992
993Below is an example where a number of ctypes objects are modified by a child
994process::
995
996 from multiprocessing import Process, Lock
997 from multiprocessing.sharedctypes import Value, Array
998 from ctypes import Structure, c_double
999
1000 class Point(Structure):
1001 _fields_ = [('x', c_double), ('y', c_double)]
1002
1003 def modify(n, x, s, A):
1004 n.value **= 2
1005 x.value **= 2
1006 s.value = s.value.upper()
1007 for a in A:
1008 a.x **= 2
1009 a.y **= 2
1010
1011 if __name__ == '__main__':
1012 lock = Lock()
1013
1014 n = Value('i', 7)
1015 x = Value(ctypes.c_double, 1.0/3.0, lock=False)
1016 s = Array('c', 'hello world', lock=lock)
1017 A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
1018
1019 p = Process(target=modify, args=(n, x, s, A))
1020 p.start()
1021 p.join()
1022
1023 print n.value
1024 print x.value
1025 print s.value
1026 print [(a.x, a.y) for a in A]
1027
1028
1029.. highlightlang:: none
1030
1031The results printed are ::
1032
1033 49
1034 0.1111111111111111
1035 HELLO WORLD
1036 [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
1037
1038.. highlightlang:: python
1039
1040
1041.. _multiprocessing-managers:
1042
1043Managers
1044~~~~~~~~
1045
1046Managers provide a way to create data which can be shared between different
1047processes. A manager object controls a server process which manages *shared
1048objects*. Other processes can access the shared objects by using proxies.
1049
1050.. function:: multiprocessing.Manager()
1051
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001052 Returns a started :class:`~multiprocessing.managers.SyncManager` object which
1053 can be used for sharing objects between processes. The returned manager
1054 object corresponds to a spawned child process and has methods which will
1055 create shared objects and return corresponding proxies.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001056
1057.. module:: multiprocessing.managers
1058 :synopsis: Share data between process with shared objects.
1059
1060Manager processes will be shutdown as soon as they are garbage collected or
1061their parent process exits. The manager classes are defined in the
1062:mod:`multiprocessing.managers` module:
1063
1064.. class:: BaseManager([address[, authkey]])
1065
1066 Create a BaseManager object.
1067
1068 Once created one should call :meth:`start` or :meth:`serve_forever` to ensure
1069 that the manager object refers to a started manager process.
1070
1071 *address* is the address on which the manager process listens for new
1072 connections. If *address* is ``None`` then an arbitrary one is chosen.
1073
1074 *authkey* is the authentication key which will be used to check the validity
1075 of incoming connections to the server process. If *authkey* is ``None`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001076 ``current_process().authkey``. Otherwise *authkey* is used and it
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001077 must be a string.
1078
1079 .. method:: start()
1080
1081 Start a subprocess to start the manager.
1082
Andrew M. Kuchlinga2478d92008-07-14 00:40:55 +00001083 .. method:: serve_forever()
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001084
1085 Run the server in the current process.
1086
1087 .. method:: from_address(address, authkey)
1088
1089 A class method which creates a manager object referring to a pre-existing
1090 server process which is using the given address and authentication key.
1091
1092 .. method:: shutdown()
1093
1094 Stop the process used by the manager. This is only available if
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001095 :meth:`start` has been used to start the server process.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001096
1097 This can be called multiple times.
1098
1099 .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])
1100
1101 A classmethod which can be used for registering a type or callable with
1102 the manager class.
1103
1104 *typeid* is a "type identifier" which is used to identify a particular
1105 type of shared object. This must be a string.
1106
1107 *callable* is a callable used for creating objects for this type
1108 identifier. If a manager instance will be created using the
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001109 :meth:`from_address` classmethod or if the *create_method* argument is
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001110 ``False`` then this can be left as ``None``.
1111
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001112 *proxytype* is a subclass of :class:`BaseProxy` which is used to create
1113 proxies for shared objects with this *typeid*. If ``None`` then a proxy
1114 class is created automatically.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001115
1116 *exposed* is used to specify a sequence of method names which proxies for
1117 this typeid should be allowed to access using
1118 :meth:`BaseProxy._callMethod`. (If *exposed* is ``None`` then
1119 :attr:`proxytype._exposed_` is used instead if it exists.) In the case
1120 where no exposed list is specified, all "public methods" of the shared
1121 object will be accessible. (Here a "public method" means any attribute
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001122 which has a :meth:`__call__` method and whose name does not begin with
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001123 ``'_'``.)
1124
1125 *method_to_typeid* is a mapping used to specify the return type of those
1126 exposed methods which should return a proxy. It maps method names to
1127 typeid strings. (If *method_to_typeid* is ``None`` then
1128 :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a
1129 method's name is not a key of this mapping or if the mapping is ``None``
1130 then the object returned by the method will be copied by value.
1131
1132 *create_method* determines whether a method should be created with name
1133 *typeid* which can be used to tell the server process to create a new
1134 shared object and return a proxy for it. By default it is ``True``.
1135
1136 :class:`BaseManager` instances also have one read-only property:
1137
1138 .. attribute:: address
1139
1140 The address used by the manager.
1141
1142
1143.. class:: SyncManager
1144
1145 A subclass of :class:`BaseManager` which can be used for the synchronization
1146 of processes. Objects of this type are returned by
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001147 :func:`multiprocessing.Manager`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001148
1149 It also supports creation of shared lists and dictionaries.
1150
1151 .. method:: BoundedSemaphore([value])
1152
1153 Create a shared :class:`threading.BoundedSemaphore` object and return a
1154 proxy for it.
1155
1156 .. method:: Condition([lock])
1157
1158 Create a shared :class:`threading.Condition` object and return a proxy for
1159 it.
1160
1161 If *lock* is supplied then it should be a proxy for a
1162 :class:`threading.Lock` or :class:`threading.RLock` object.
1163
1164 .. method:: Event()
1165
1166 Create a shared :class:`threading.Event` object and return a proxy for it.
1167
1168 .. method:: Lock()
1169
1170 Create a shared :class:`threading.Lock` object and return a proxy for it.
1171
1172 .. method:: Namespace()
1173
1174 Create a shared :class:`Namespace` object and return a proxy for it.
1175
1176 .. method:: Queue([maxsize])
1177
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001178 Create a shared :class:`Queue.Queue` object and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001179
1180 .. method:: RLock()
1181
1182 Create a shared :class:`threading.RLock` object and return a proxy for it.
1183
1184 .. method:: Semaphore([value])
1185
1186 Create a shared :class:`threading.Semaphore` object and return a proxy for
1187 it.
1188
1189 .. method:: Array(typecode, sequence)
1190
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001191 Create an array and return a proxy for it.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001192
1193 .. method:: Value(typecode, value)
1194
1195 Create an object with a writable ``value`` attribute and return a proxy
1196 for it.
1197
1198 .. method:: dict()
1199 dict(mapping)
1200 dict(sequence)
1201
1202 Create a shared ``dict`` object and return a proxy for it.
1203
1204 .. method:: list()
1205 list(sequence)
1206
1207 Create a shared ``list`` object and return a proxy for it.
1208
1209
1210Namespace objects
1211>>>>>>>>>>>>>>>>>
1212
1213A namespace object has no public methods, but does have writable attributes.
1214Its representation shows the values of its attributes.
1215
1216However, when using a proxy for a namespace object, an attribute beginning with
1217``'_'`` will be an attribute of the proxy and not an attribute of the referent::
1218
1219 >>> manager = multiprocessing.Manager()
1220 >>> Global = manager.Namespace()
1221 >>> Global.x = 10
1222 >>> Global.y = 'hello'
1223 >>> Global._z = 12.3 # this is an attribute of the proxy
1224 >>> print Global
1225 Namespace(x=10, y='hello')
1226
1227
1228Customized managers
1229>>>>>>>>>>>>>>>>>>>
1230
1231To create one's own manager, one creates a subclass of :class:`BaseManager` and
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001232use the :meth:`~BaseManager.resgister` classmethod to register new types or
1233callables with the manager class. For example::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001234
1235 from multiprocessing.managers import BaseManager
1236
1237 class MathsClass(object):
1238 def add(self, x, y):
1239 return x + y
1240 def mul(self, x, y):
1241 return x * y
1242
1243 class MyManager(BaseManager):
1244 pass
1245
1246 MyManager.register('Maths', MathsClass)
1247
1248 if __name__ == '__main__':
1249 manager = MyManager()
1250 manager.start()
1251 maths = manager.Maths()
1252 print maths.add(4, 3) # prints 7
1253 print maths.mul(7, 8) # prints 56
1254
1255
1256Using a remote manager
1257>>>>>>>>>>>>>>>>>>>>>>
1258
1259It is possible to run a manager server on one machine and have clients use it
1260from other machines (assuming that the firewalls involved allow it).
1261
1262Running the following commands creates a server for a single shared queue which
1263remote clients can access::
1264
1265 >>> from multiprocessing.managers import BaseManager
1266 >>> import Queue
1267 >>> queue = Queue.Queue()
1268 >>> class QueueManager(BaseManager): pass
1269 ...
1270 >>> QueueManager.register('getQueue', callable=lambda:queue)
1271 >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
1272 >>> m.serveForever()
1273
1274One client can access the server as follows::
1275
1276 >>> from multiprocessing.managers import BaseManager
1277 >>> class QueueManager(BaseManager): pass
1278 ...
1279 >>> QueueManager.register('getQueue')
1280 >>> m = QueueManager.from_address(address=('foo.bar.org', 50000),
1281 >>> authkey='abracadabra')
1282 >>> queue = m.getQueue()
1283 >>> queue.put('hello')
1284
1285Another client can also use it::
1286
1287 >>> from multiprocessing.managers import BaseManager
1288 >>> class QueueManager(BaseManager): pass
1289 ...
1290 >>> QueueManager.register('getQueue')
1291 >>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='abracadabra')
1292 >>> queue = m.getQueue()
1293 >>> queue.get()
1294 'hello'
1295
1296
1297Proxy Objects
1298~~~~~~~~~~~~~
1299
1300A proxy is an object which *refers* to a shared object which lives (presumably)
1301in a different process. The shared object is said to be the *referent* of the
1302proxy. Multiple proxy objects may have the same referent.
1303
1304A proxy object has methods which invoke corresponding methods of its referent
1305(although not every method of the referent will necessarily be available through
1306the proxy). A proxy can usually be used in most of the same ways that its
1307referent can::
1308
1309 >>> from multiprocessing import Manager
1310 >>> manager = Manager()
1311 >>> l = manager.list([i*i for i in range(10)])
1312 >>> print l
1313 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1314 >>> print repr(l)
1315 <ListProxy object, typeid 'list' at 0xb799974c>
1316 >>> l[4]
1317 16
1318 >>> l[2:5]
1319 [4, 9, 16]
1320
1321Notice that applying :func:`str` to a proxy will return the representation of
1322the referent, whereas applying :func:`repr` will return the representation of
1323the proxy.
1324
1325An important feature of proxy objects is that they are picklable so they can be
1326passed between processes. Note, however, that if a proxy is sent to the
1327corresponding manager's process then unpickling it will produce the referent
1328itself. This means, for example, that one shared object can contain a second::
1329
1330 >>> a = manager.list()
1331 >>> b = manager.list()
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001332 >>> a.append(b) # referent of a now contains referent of b
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001333 >>> print a, b
1334 [[]] []
1335 >>> b.append('hello')
1336 >>> print a, b
1337 [['hello']] ['hello']
1338
1339.. note::
1340
1341 The proxy types in :mod:`multiprocessing` do nothing to support comparisons
1342 by value. So, for instance, ::
1343
1344 manager.list([1,2,3]) == [1,2,3]
1345
1346 will return ``False``. One should just use a copy of the referent instead
1347 when making comparisons.
1348
1349.. class:: BaseProxy
1350
1351 Proxy objects are instances of subclasses of :class:`BaseProxy`.
1352
1353 .. method:: _call_method(methodname[, args[, kwds]])
1354
1355 Call and return the result of a method of the proxy's referent.
1356
1357 If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
1358
1359 proxy._call_method(methodname, args, kwds)
1360
1361 will evaluate the expression ::
1362
1363 getattr(obj, methodname)(*args, **kwds)
1364
1365 in the manager's process.
1366
1367 The returned value will be a copy of the result of the call or a proxy to
1368 a new shared object -- see documentation for the *method_to_typeid*
1369 argument of :meth:`BaseManager.register`.
1370
1371 If an exception is raised by the call, then then is re-raised by
1372 :meth:`_call_method`. If some other exception is raised in the manager's
1373 process then this is converted into a :exc:`RemoteError` exception and is
1374 raised by :meth:`_call_method`.
1375
1376 Note in particular that an exception will be raised if *methodname* has
1377 not been *exposed*
1378
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001379 An example of the usage of :meth:`_call_method`::
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001380
1381 >>> l = manager.list(range(10))
1382 >>> l._call_method('__len__')
1383 10
1384 >>> l._call_method('__getslice__', (2, 7)) # equiv to `l[2:7]`
1385 [2, 3, 4, 5, 6]
1386 >>> l._call_method('__getitem__', (20,)) # equiv to `l[20]`
1387 Traceback (most recent call last):
1388 ...
1389 IndexError: list index out of range
1390
1391 .. method:: _get_value()
1392
1393 Return a copy of the referent.
1394
1395 If the referent is unpicklable then this will raise an exception.
1396
1397 .. method:: __repr__
1398
1399 Return a representation of the proxy object.
1400
1401 .. method:: __str__
1402
1403 Return the representation of the referent.
1404
1405
1406Cleanup
1407>>>>>>>
1408
1409A proxy object uses a weakref callback so that when it gets garbage collected it
1410deregisters itself from the manager which owns its referent.
1411
1412A shared object gets deleted from the manager process when there are no longer
1413any proxies referring to it.
1414
1415
1416Process Pools
1417~~~~~~~~~~~~~
1418
1419.. module:: multiprocessing.pool
1420 :synopsis: Create pools of processes.
1421
1422One can create a pool of processes which will carry out tasks submitted to it
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001423with the :class:`Pool` class.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001424
1425.. class:: multiprocessing.Pool([processes[, initializer[, initargs]]])
1426
1427 A process pool object which controls a pool of worker processes to which jobs
1428 can be submitted. It supports asynchronous results with timeouts and
1429 callbacks and has a parallel map implementation.
1430
1431 *processes* is the number of worker processes to use. If *processes* is
1432 ``None`` then the number returned by :func:`cpu_count` is used. If
1433 *initializer* is not ``None`` then each worker process will call
1434 ``initializer(*initargs)`` when it starts.
1435
1436 .. method:: apply(func[, args[, kwds]])
1437
1438 Equivalent of the :func:`apply` builtin function. It blocks till the
1439 result is ready.
1440
1441 .. method:: apply_async(func[, args[, kwds[, callback]]])
1442
1443 A variant of the :meth:`apply` method which returns a result object.
1444
1445 If *callback* is specified then it should be a callable which accepts a
1446 single argument. When the result becomes ready *callback* is applied to
1447 it (unless the call failed). *callback* should complete immediately since
1448 otherwise the thread which handles the results will get blocked.
1449
1450 .. method:: map(func, iterable[, chunksize])
1451
1452 A parallel equivalent of the :func:`map` builtin function. It blocks till
1453 the result is ready.
1454
1455 This method chops the iterable into a number of chunks which it submits to
1456 the process pool as separate tasks. The (approximate) size of these
1457 chunks can be specified by setting *chunksize* to a positive integer.
1458
1459 .. method:: map_async(func, iterable[, chunksize[, callback]])
1460
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001461 A variant of the :meth:`map` method which returns a result object.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001462
1463 If *callback* is specified then it should be a callable which accepts a
1464 single argument. When the result becomes ready *callback* is applied to
1465 it (unless the call failed). *callback* should complete immediately since
1466 otherwise the thread which handles the results will get blocked.
1467
1468 .. method:: imap(func, iterable[, chunksize])
1469
1470 An equivalent of :func:`itertools.imap`.
1471
1472 The *chunksize* argument is the same as the one used by the :meth:`.map`
1473 method. For very long iterables using a large value for *chunksize* can
1474 make make the job complete **much** faster than using the default value of
1475 ``1``.
1476
1477 Also if *chunksize* is ``1`` then the :meth:`next` method of the iterator
1478 returned by the :meth:`imap` method has an optional *timeout* parameter:
1479 ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
1480 result cannot be returned within *timeout* seconds.
1481
1482 .. method:: imap_unordered(func, iterable[, chunksize])
1483
1484 The same as :meth:`imap` except that the ordering of the results from the
1485 returned iterator should be considered arbitrary. (Only when there is
1486 only one worker process is the order guaranteed to be "correct".)
1487
1488 .. method:: close()
1489
1490 Prevents any more tasks from being submitted to the pool. Once all the
1491 tasks have been completed the worker processes will exit.
1492
1493 .. method:: terminate()
1494
1495 Stops the worker processes immediately without completing outstanding
1496 work. When the pool object is garbage collected :meth:`terminate` will be
1497 called immediately.
1498
1499 .. method:: join()
1500
1501 Wait for the worker processes to exit. One must call :meth:`close` or
1502 :meth:`terminate` before using :meth:`join`.
1503
1504
1505.. class:: AsyncResult
1506
1507 The class of the result returned by :meth:`Pool.apply_async` and
1508 :meth:`Pool.map_async`.
1509
1510 .. method:: get([timeout)
1511
1512 Return the result when it arrives. If *timeout* is not ``None`` and the
1513 result does not arrive within *timeout* seconds then
1514 :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised
1515 an exception then that exception will be reraised by :meth:`get`.
1516
1517 .. method:: wait([timeout])
1518
1519 Wait until the result is available or until *timeout* seconds pass.
1520
1521 .. method:: ready()
1522
1523 Return whether the call has completed.
1524
1525 .. method:: successful()
1526
1527 Return whether the call completed without raising an exception. Will
1528 raise :exc:`AssertionError` if the result is not ready.
1529
1530The following example demonstrates the use of a pool::
1531
1532 from multiprocessing import Pool
1533
1534 def f(x):
1535 return x*x
1536
1537 if __name__ == '__main__':
1538 pool = Pool(processes=4) # start 4 worker processes
1539
1540 result = pool.applyAsync(f, (10,)) # evaluate "f(10)" asynchronously
1541 print result.get(timeout=1) # prints "100" unless your computer is *very* slow
1542
1543 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
1544
1545 it = pool.imap(f, range(10))
1546 print it.next() # prints "0"
1547 print it.next() # prints "1"
1548 print it.next(timeout=1) # prints "4" unless your computer is *very* slow
1549
1550 import time
1551 result = pool.applyAsync(time.sleep, (10,))
1552 print result.get(timeout=1) # raises TimeoutError
1553
1554
1555.. _multiprocessing-listeners-clients:
1556
1557Listeners and Clients
1558~~~~~~~~~~~~~~~~~~~~~
1559
1560.. module:: multiprocessing.connection
1561 :synopsis: API for dealing with sockets.
1562
1563Usually message passing between processes is done using queues or by using
1564:class:`Connection` objects returned by :func:`Pipe`.
1565
1566However, the :mod:`multiprocessing.connection` module allows some extra
1567flexibility. It basically gives a high level message oriented API for dealing
1568with sockets or Windows named pipes, and also has support for *digest
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001569authentication* using the :mod:`hmac` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001570
1571
1572.. function:: deliver_challenge(connection, authkey)
1573
1574 Send a randomly generated message to the other end of the connection and wait
1575 for a reply.
1576
1577 If the reply matches the digest of the message using *authkey* as the key
1578 then a welcome message is sent to the other end of the connection. Otherwise
1579 :exc:`AuthenticationError` is raised.
1580
1581.. function:: answerChallenge(connection, authkey)
1582
1583 Receive a message, calculate the digest of the message using *authkey* as the
1584 key, and then send the digest back.
1585
1586 If a welcome message is not received, then :exc:`AuthenticationError` is
1587 raised.
1588
1589.. function:: Client(address[, family[, authenticate[, authkey]]])
1590
1591 Attempt to set up a connection to the listener which is using address
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001592 *address*, returning a :class:`~multiprocessing.Connection`.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001593
1594 The type of the connection is determined by *family* argument, but this can
1595 generally be omitted since it can usually be inferred from the format of
1596 *address*. (See :ref:`multiprocessing-address-formats`)
1597
1598 If *authentication* is ``True`` or *authkey* is a string then digest
1599 authentication is used. The key used for authentication will be either
Benjamin Peterson73641d72008-08-20 14:07:59 +00001600 *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001601 If authentication fails then :exc:`AuthenticationError` is raised. See
1602 :ref:`multiprocessing-auth-keys`.
1603
1604.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])
1605
1606 A wrapper for a bound socket or Windows named pipe which is 'listening' for
1607 connections.
1608
1609 *address* is the address to be used by the bound socket or named pipe of the
1610 listener object.
1611
1612 *family* is the type of socket (or named pipe) to use. This can be one of
1613 the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
1614 domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only
1615 the first is guaranteed to be available. If *family* is ``None`` then the
1616 family is inferred from the format of *address*. If *address* is also
1617 ``None`` then a default is chosen. This default is the family which is
1618 assumed to be the fastest available. See
1619 :ref:`multiprocessing-address-formats`. Note that if *family* is
1620 ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
1621 private temporary directory created using :func:`tempfile.mkstemp`.
1622
1623 If the listener object uses a socket then *backlog* (1 by default) is passed
1624 to the :meth:`listen` method of the socket once it has been bound.
1625
1626 If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
1627 ``None`` then digest authentication is used.
1628
1629 If *authkey* is a string then it will be used as the authentication key;
1630 otherwise it must be *None*.
1631
1632 If *authkey* is ``None`` and *authenticate* is ``True`` then
Benjamin Peterson73641d72008-08-20 14:07:59 +00001633 ``current_process().authkey`` is used as the authentication key. If
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001634 *authkey* is ``None`` and *authentication* is ``False`` then no
1635 authentication is done. If authentication fails then
1636 :exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
1637
1638 .. method:: accept()
1639
1640 Accept a connection on the bound socket or named pipe of the listener
1641 object and return a :class:`Connection` object. If authentication is
1642 attempted and fails, then :exc:`AuthenticationError` is raised.
1643
1644 .. method:: close()
1645
1646 Close the bound socket or named pipe of the listener object. This is
1647 called automatically when the listener is garbage collected. However it
1648 is advisable to call it explicitly.
1649
1650 Listener objects have the following read-only properties:
1651
1652 .. attribute:: address
1653
1654 The address which is being used by the Listener object.
1655
1656 .. attribute:: last_accepted
1657
1658 The address from which the last accepted connection came. If this is
1659 unavailable then it is ``None``.
1660
1661
1662The module defines two exceptions:
1663
1664.. exception:: AuthenticationError
1665
1666 Exception raised when there is an authentication error.
1667
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001668
1669**Examples**
1670
1671The following server code creates a listener which uses ``'secret password'`` as
1672an authentication key. It then waits for a connection and sends some data to
1673the client::
1674
1675 from multiprocessing.connection import Listener
1676 from array import array
1677
1678 address = ('localhost', 6000) # family is deduced to be 'AF_INET'
1679 listener = Listener(address, authkey='secret password')
1680
1681 conn = listener.accept()
1682 print 'connection accepted from', listener.last_accepted
1683
1684 conn.send([2.25, None, 'junk', float])
1685
1686 conn.send_bytes('hello')
1687
1688 conn.send_bytes(array('i', [42, 1729]))
1689
1690 conn.close()
1691 listener.close()
1692
1693The following code connects to the server and receives some data from the
1694server::
1695
1696 from multiprocessing.connection import Client
1697 from array import array
1698
1699 address = ('localhost', 6000)
1700 conn = Client(address, authkey='secret password')
1701
1702 print conn.recv() # => [2.25, None, 'junk', float]
1703
1704 print conn.recv_bytes() # => 'hello'
1705
1706 arr = array('i', [0, 0, 0, 0, 0])
1707 print conn.recv_bytes_into(arr) # => 8
1708 print arr # => array('i', [42, 1729, 0, 0, 0])
1709
1710 conn.close()
1711
1712
1713.. _multiprocessing-address-formats:
1714
1715Address Formats
1716>>>>>>>>>>>>>>>
1717
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001718* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001719 *hostname* is a string and *port* is an integer.
1720
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001721* An ``'AF_UNIX'`` address is a string representing a filename on the
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001722 filesystem.
1723
1724* An ``'AF_PIPE'`` address is a string of the form
1725 ``r'\\\\.\\pipe\\PipeName'``. To use :func:`Client` to connect to a named
1726 pipe on a remote computer called ServerName* one should use an address of the
1727 form ``r'\\\\ServerName\\pipe\\PipeName'`` instead.
1728
1729Note that any string beginning with two backslashes is assumed by default to be
1730an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
1731
1732
1733.. _multiprocessing-auth-keys:
1734
1735Authentication keys
1736~~~~~~~~~~~~~~~~~~~
1737
1738When one uses :meth:`Connection.recv`, the data received is automatically
1739unpickled. Unfortunately unpickling data from an untrusted source is a security
1740risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
1741to provide digest authentication.
1742
1743An authentication key is a string which can be thought of as a password: once a
1744connection is established both ends will demand proof that the other knows the
1745authentication key. (Demonstrating that both ends are using the same key does
1746**not** involve sending the key over the connection.)
1747
1748If authentication is requested but do authentication key is specified then the
Benjamin Peterson73641d72008-08-20 14:07:59 +00001749return value of ``current_process().authkey`` is used (see
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001750:class:`~multiprocessing.Process`). This value will automatically inherited by
1751any :class:`~multiprocessing.Process` object that the current process creates.
1752This means that (by default) all processes of a multi-process program will share
1753a single authentication key which can be used when setting up connections
1754between the themselves.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001755
1756Suitable authentication keys can also be generated by using :func:`os.urandom`.
1757
1758
1759Logging
1760~~~~~~~
1761
1762Some support for logging is available. Note, however, that the :mod:`logging`
1763package does not use process shared locks so it is possible (depending on the
1764handler type) for messages from different processes to get mixed up.
1765
1766.. currentmodule:: multiprocessing
1767.. function:: get_logger()
1768
1769 Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
1770 will be created.
1771
1772 When first created the logger has level :data:`logging.NOTSET` and has a
1773 handler which sends output to :data:`sys.stderr` using format
1774 ``'[%(levelname)s/%(processName)s] %(message)s'``. (The logger allows use of
1775 the non-standard ``'%(processName)s'`` format.) Message sent to this logger
Benjamin Peterson90f36732008-07-12 20:16:19 +00001776 will not by default propagate to the root logger.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001777
1778 Note that on Windows child processes will only inherit the level of the
1779 parent process's logger -- any other customization of the logger will not be
1780 inherited.
1781
1782Below is an example session with logging turned on::
1783
1784 >>> import processing, logging
1785 >>> logger = processing.getLogger()
1786 >>> logger.setLevel(logging.INFO)
1787 >>> logger.warning('doomed')
1788 [WARNING/MainProcess] doomed
1789 >>> m = processing.Manager()
1790 [INFO/SyncManager-1] child process calling self.run()
1791 [INFO/SyncManager-1] manager bound to '\\\\.\\pipe\\pyc-2776-0-lj0tfa'
1792 >>> del m
1793 [INFO/MainProcess] sending shutdown message to manager
1794 [INFO/SyncManager-1] manager exiting with exitcode 0
1795
1796
1797The :mod:`multiprocessing.dummy` module
1798~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1799
1800.. module:: multiprocessing.dummy
1801 :synopsis: Dumb wrapper around threading.
1802
1803:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001804no more than a wrapper around the :mod:`threading` module.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001805
1806
1807.. _multiprocessing-programming:
1808
1809Programming guidelines
1810----------------------
1811
1812There are certain guidelines and idioms which should be adhered to when using
1813:mod:`multiprocessing`.
1814
1815
1816All platforms
1817~~~~~~~~~~~~~
1818
1819Avoid shared state
1820
1821 As far as possible one should try to avoid shifting large amounts of data
1822 between processes.
1823
1824 It is probably best to stick to using queues or pipes for communication
1825 between processes rather than using the lower level synchronization
1826 primitives from the :mod:`threading` module.
1827
1828Picklability
1829
1830 Ensure that the arguments to the methods of proxies are picklable.
1831
1832Thread safety of proxies
1833
1834 Do not use a proxy object from more than one thread unless you protect it
1835 with a lock.
1836
1837 (There is never a problem with different processes using the *same* proxy.)
1838
1839Joining zombie processes
1840
1841 On Unix when a process finishes but has not been joined it becomes a zombie.
1842 There should never be very many because each time a new process starts (or
1843 :func:`active_children` is called) all completed processes which have not
1844 yet been joined will be joined. Also calling a finished process's
1845 :meth:`Process.is_alive` will join the process. Even so it is probably good
1846 practice to explicitly join all the processes that you start.
1847
1848Better to inherit than pickle/unpickle
1849
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001850 On Windows many types from :mod:`multiprocessing` need to be picklable so
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001851 that child processes can use them. However, one should generally avoid
1852 sending shared objects to other processes using pipes or queues. Instead
1853 you should arrange the program so that a process which need access to a
1854 shared resource created elsewhere can inherit it from an ancestor process.
1855
1856Avoid terminating processes
1857
1858 Using the :meth:`Process.terminate` method to stop a process is liable to
1859 cause any shared resources (such as locks, semaphores, pipes and queues)
1860 currently being used by the process to become broken or unavailable to other
1861 processes.
1862
1863 Therefore it is probably best to only consider using
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001864 :meth:`Process.terminate` on processes which never use any shared resources.
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001865
1866Joining processes that use queues
1867
1868 Bear in mind that a process that has put items in a queue will wait before
1869 terminating until all the buffered items are fed by the "feeder" thread to
1870 the underlying pipe. (The child process can call the
Jesse Nollerd5ff5b22008-09-06 01:20:11 +00001871 :meth:`Queue.cancel_join_thread` method of the queue to avoid this behaviour.)
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001872
1873 This means that whenever you use a queue you need to make sure that all
1874 items which have been put on the queue will eventually be removed before the
1875 process is joined. Otherwise you cannot be sure that processes which have
1876 put items on the queue will terminate. Remember also that non-daemonic
1877 processes will be automatically be joined.
1878
1879 An example which will deadlock is the following::
1880
1881 from multiprocessing import Process, Queue
1882
1883 def f(q):
1884 q.put('X' * 1000000)
1885
1886 if __name__ == '__main__':
1887 queue = Queue()
1888 p = Process(target=f, args=(queue,))
1889 p.start()
1890 p.join() # this deadlocks
1891 obj = queue.get()
1892
1893 A fix here would be to swap the last two lines round (or simply remove the
1894 ``p.join()`` line).
1895
Andrew M. Kuchlingbe504f12008-06-19 19:48:42 +00001896Explicitly pass resources to child processes
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001897
1898 On Unix a child process can make use of a shared resource created in a
1899 parent process using a global resource. However, it is better to pass the
1900 object as an argument to the constructor for the child process.
1901
1902 Apart from making the code (potentially) compatible with Windows this also
1903 ensures that as long as the child process is still alive the object will not
1904 be garbage collected in the parent process. This might be important if some
1905 resource is freed when the object is garbage collected in the parent
1906 process.
1907
1908 So for instance ::
1909
1910 from multiprocessing import Process, Lock
1911
1912 def f():
1913 ... do something using "lock" ...
1914
1915 if __name__ == '__main__':
1916 lock = Lock()
1917 for i in range(10):
1918 Process(target=f).start()
1919
1920 should be rewritten as ::
1921
1922 from multiprocessing import Process, Lock
1923
1924 def f(l):
1925 ... do something using "l" ...
1926
1927 if __name__ == '__main__':
1928 lock = Lock()
1929 for i in range(10):
1930 Process(target=f, args=(lock,)).start()
1931
1932
1933Windows
1934~~~~~~~
1935
1936Since Windows lacks :func:`os.fork` it has a few extra restrictions:
1937
1938More picklability
1939
1940 Ensure that all arguments to :meth:`Process.__init__` are picklable. This
1941 means, in particular, that bound or unbound methods cannot be used directly
1942 as the ``target`` argument on Windows --- just define a function and use
1943 that instead.
1944
1945 Also, if you subclass :class:`Process` then make sure that instances will be
1946 picklable when the :meth:`Process.start` method is called.
1947
1948Global variables
1949
1950 Bear in mind that if code run in a child process tries to access a global
1951 variable, then the value it sees (if any) may not be the same as the value
1952 in the parent process at the time that :meth:`Process.start` was called.
1953
1954 However, global variables which are just module level constants cause no
1955 problems.
1956
1957Safe importing of main module
1958
1959 Make sure that the main module can be safely imported by a new Python
1960 interpreter without causing unintended side effects (such a starting a new
1961 process).
1962
1963 For example, under Windows running the following module would fail with a
1964 :exc:`RuntimeError`::
1965
1966 from multiprocessing import Process
1967
1968 def foo():
1969 print 'hello'
1970
1971 p = Process(target=foo)
1972 p.start()
1973
1974 Instead one should protect the "entry point" of the program by using ``if
1975 __name__ == '__main__':`` as follows::
1976
1977 from multiprocessing import Process, freeze_support
1978
1979 def foo():
1980 print 'hello'
1981
1982 if __name__ == '__main__':
1983 freeze_support()
1984 p = Process(target=foo)
1985 p.start()
1986
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00001987 (The ``freeze_support()`` line can be omitted if the program will be run
Benjamin Peterson190d56e2008-06-11 02:40:25 +00001988 normally instead of frozen.)
1989
1990 This allows the newly spawned Python interpreter to safely import the module
1991 and then run the module's ``foo()`` function.
1992
1993 Similar restrictions apply if a pool or manager is created in the main
1994 module.
1995
1996
1997.. _multiprocessing-examples:
1998
1999Examples
2000--------
2001
2002Demonstration of how to create and use customized managers and proxies:
2003
2004.. literalinclude:: ../includes/mp_newtype.py
2005
2006
2007Using :class:`Pool`:
2008
2009.. literalinclude:: ../includes/mp_pool.py
2010
2011
2012Synchronization types like locks, conditions and queues:
2013
2014.. literalinclude:: ../includes/mp_synchronize.py
2015
2016
2017An showing how to use queues to feed tasks to a collection of worker process and
2018collect the results:
2019
2020.. literalinclude:: ../includes/mp_workers.py
2021
2022
2023An example of how a pool of worker processes can each run a
2024:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
2025socket.
2026
2027.. literalinclude:: ../includes/mp_webserver.py
2028
2029
2030Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:
2031
2032.. literalinclude:: ../includes/mp_benchmarks.py
2033
2034An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process`
2035and others to build a system which can distribute processes and work via a
2036distributed queue to a "cluster" of machines on a network, accessible via SSH.
2037You will need to have private key authentication for all hosts configured for
2038this to work.
2039
Benjamin Peterson910c2ab2008-06-27 23:22:06 +00002040.. literalinclude:: ../includes/mp_distributing.py