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