blob: 1f3e67c9b8b4f7a959a5466c364500dd178f102a [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Package analogous to 'threading.py' but using processes
3#
4# multiprocessing/__init__.py
5#
6# This package is intended to duplicate the functionality (and much of
7# the API) of threading.py but uses processes instead of threads. A
8# subpackage 'multiprocessing.dummy' has the same API but is a simple
9# wrapper for 'threading'.
10#
11# Try calling `multiprocessing.doc.main()` to read the html
Ezio Melottie130a522011-10-19 10:58:56 +030012# documentation in a webbrowser.
Benjamin Petersone711caf2008-06-11 16:44:04 +000013#
14#
15# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +010016# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +000017#
18
19__version__ = '0.70a1'
20
21__all__ = [
22 'Process', 'current_process', 'active_children', 'freeze_support',
23 'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger',
24 'allow_connection_pickling', 'BufferTooShort', 'TimeoutError',
25 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
Richard Oudkerk3730a172012-06-15 18:26:07 +010026 'Event', 'Barrier', 'Queue', 'SimpleQueue', 'JoinableQueue', 'Pool',
27 'Value', 'Array', 'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING',
Benjamin Petersone711caf2008-06-11 16:44:04 +000028 ]
29
30__author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)'
31
32#
33# Imports
34#
35
36import os
37import sys
38
39from multiprocessing.process import Process, current_process, active_children
Jesse Noller41faa542009-01-25 03:45:53 +000040from multiprocessing.util import SUBDEBUG, SUBWARNING
Benjamin Petersone711caf2008-06-11 16:44:04 +000041
42#
43# Exceptions
44#
45
46class ProcessError(Exception):
47 pass
48
49class BufferTooShort(ProcessError):
50 pass
51
52class TimeoutError(ProcessError):
53 pass
54
55class AuthenticationError(ProcessError):
56 pass
57
58import _multiprocessing
59
60#
61# Definitions not depending on native semaphores
62#
63
64def Manager():
65 '''
66 Returns a manager associated with a running server process
67
68 The managers methods such as `Lock()`, `Condition()` and `Queue()`
69 can be used to create shared objects.
70 '''
71 from multiprocessing.managers import SyncManager
72 m = SyncManager()
73 m.start()
74 return m
75
76def Pipe(duplex=True):
77 '''
78 Returns two connection object connected by a pipe
79 '''
80 from multiprocessing.connection import Pipe
81 return Pipe(duplex)
82
83def cpu_count():
84 '''
85 Returns the number of CPUs in the system
86 '''
87 if sys.platform == 'win32':
88 try:
89 num = int(os.environ['NUMBER_OF_PROCESSORS'])
90 except (ValueError, KeyError):
91 num = 0
Benjamin Peterson4469d0c2008-11-30 22:46:23 +000092 elif 'bsd' in sys.platform or sys.platform == 'darwin':
Ronald Oussoren0b8753d2011-03-16 09:41:32 -040093 comm = '/sbin/sysctl -n hw.ncpu'
94 if sys.platform == 'darwin':
95 comm = '/usr' + comm
Benjamin Petersone711caf2008-06-11 16:44:04 +000096 try:
Ronald Oussoren0b8753d2011-03-16 09:41:32 -040097 with os.popen(comm) as p:
Brian Curtin50be1ca2010-11-01 05:10:44 +000098 num = int(p.read())
Benjamin Petersone711caf2008-06-11 16:44:04 +000099 except ValueError:
100 num = 0
101 else:
102 try:
103 num = os.sysconf('SC_NPROCESSORS_ONLN')
104 except (ValueError, OSError, AttributeError):
105 num = 0
106
107 if num >= 1:
108 return num
109 else:
110 raise NotImplementedError('cannot determine number of cpus')
111
112def freeze_support():
113 '''
114 Check whether this is a fake forked process in a frozen executable.
115 If so then run code specified by commandline and exit.
116 '''
117 if sys.platform == 'win32' and getattr(sys, 'frozen', False):
118 from multiprocessing.forking import freeze_support
119 freeze_support()
120
121def get_logger():
122 '''
123 Return package logger -- if it does not already exist then it is created
124 '''
125 from multiprocessing.util import get_logger
126 return get_logger()
127
128def log_to_stderr(level=None):
129 '''
130 Turn on logging and add a handler which prints to stderr
131 '''
132 from multiprocessing.util import log_to_stderr
133 return log_to_stderr(level)
134
135def allow_connection_pickling():
136 '''
137 Install support for sending connections and sockets between processes
138 '''
Antoine Pitrou5438ed12012-04-24 22:56:57 +0200139 # This is undocumented. In previous versions of multiprocessing
140 # its only effect was to make socket objects inheritable on Windows.
141 import multiprocessing.connection
Benjamin Petersone711caf2008-06-11 16:44:04 +0000142
143#
144# Definitions depending on native semaphores
145#
146
147def Lock():
148 '''
149 Returns a non-recursive lock object
150 '''
151 from multiprocessing.synchronize import Lock
152 return Lock()
153
154def RLock():
155 '''
156 Returns a recursive lock object
157 '''
158 from multiprocessing.synchronize import RLock
159 return RLock()
160
161def Condition(lock=None):
162 '''
163 Returns a condition object
164 '''
165 from multiprocessing.synchronize import Condition
166 return Condition(lock)
167
168def Semaphore(value=1):
169 '''
170 Returns a semaphore object
171 '''
172 from multiprocessing.synchronize import Semaphore
173 return Semaphore(value)
174
175def BoundedSemaphore(value=1):
176 '''
177 Returns a bounded semaphore object
178 '''
179 from multiprocessing.synchronize import BoundedSemaphore
180 return BoundedSemaphore(value)
181
182def Event():
183 '''
184 Returns an event object
185 '''
186 from multiprocessing.synchronize import Event
187 return Event()
188
Richard Oudkerk3730a172012-06-15 18:26:07 +0100189def Barrier(parties, action=None, timeout=None):
190 '''
191 Returns a barrier object
192 '''
193 from multiprocessing.synchronize import Barrier
194 return Barrier(parties, action, timeout)
195
Benjamin Petersone711caf2008-06-11 16:44:04 +0000196def Queue(maxsize=0):
197 '''
198 Returns a queue object
199 '''
200 from multiprocessing.queues import Queue
201 return Queue(maxsize)
202
203def JoinableQueue(maxsize=0):
204 '''
205 Returns a queue object
206 '''
207 from multiprocessing.queues import JoinableQueue
208 return JoinableQueue(maxsize)
209
Sandro Tosicd778152012-02-15 23:27:00 +0100210def SimpleQueue():
211 '''
212 Returns a queue object
213 '''
214 from multiprocessing.queues import SimpleQueue
215 return SimpleQueue()
216
Jesse Noller1f0b6582010-01-27 03:36:01 +0000217def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000218 '''
219 Returns a process pool object
220 '''
221 from multiprocessing.pool import Pool
Jesse Noller1f0b6582010-01-27 03:36:01 +0000222 return Pool(processes, initializer, initargs, maxtasksperchild)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000223
224def RawValue(typecode_or_type, *args):
225 '''
226 Returns a shared object
227 '''
228 from multiprocessing.sharedctypes import RawValue
229 return RawValue(typecode_or_type, *args)
230
231def RawArray(typecode_or_type, size_or_initializer):
232 '''
233 Returns a shared array
234 '''
235 from multiprocessing.sharedctypes import RawArray
236 return RawArray(typecode_or_type, size_or_initializer)
237
Richard Oudkerk87ea7802012-05-29 12:01:47 +0100238def Value(typecode_or_type, *args, lock=True):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000239 '''
240 Returns a synchronized shared object
241 '''
242 from multiprocessing.sharedctypes import Value
Richard Oudkerk87ea7802012-05-29 12:01:47 +0100243 return Value(typecode_or_type, *args, lock=lock)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000244
Richard Oudkerk87ea7802012-05-29 12:01:47 +0100245def Array(typecode_or_type, size_or_initializer, *, lock=True):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000246 '''
247 Returns a synchronized shared array
248 '''
249 from multiprocessing.sharedctypes import Array
Richard Oudkerk87ea7802012-05-29 12:01:47 +0100250 return Array(typecode_or_type, size_or_initializer, lock=lock)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000251
252#
253#
254#
255
256if sys.platform == 'win32':
257
258 def set_executable(executable):
259 '''
260 Sets the path to a python.exe or pythonw.exe binary used to run
261 child processes on Windows instead of sys.executable.
262 Useful for people embedding Python.
263 '''
264 from multiprocessing.forking import set_executable
265 set_executable(executable)
266
267 __all__ += ['set_executable']