blob: 0d34b6aab97e1bcd3ead91d8d33c53eeb83d3c0b [file] [log] [blame]
Jeremy Hylton92bb6e72002-08-14 19:25:42 +00001"""Thread module emulating a subset of Java's threading model."""
Guido van Rossum7f5013a1998-04-09 22:01:42 +00002
Fred Drakea8725952002-12-30 23:32:50 +00003import sys as _sys
4
5try:
6 import thread
7except ImportError:
8 del _sys.modules[__name__]
9 raise
10
Jeffrey Yasskin105f3d42008-03-31 00:35:53 +000011import warnings
Fred Drakea8725952002-12-30 23:32:50 +000012from time import time as _time, sleep as _sleep
Neil Schemenauerf607fc52003-11-05 23:03:00 +000013from traceback import format_exc as _format_exc
Raymond Hettinger756b3f32004-01-29 06:37:52 +000014from collections import deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000015
16# Rename some stuff so "from threading import *" is safe
Guido van Rossumc262a1f2002-12-30 21:59:55 +000017__all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event',
Tim Peters685e6972003-06-29 16:50:06 +000018 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
Andrew MacIntyre92913322006-06-13 15:04:24 +000019 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000020
Guido van Rossum7f5013a1998-04-09 22:01:42 +000021_start_new_thread = thread.start_new_thread
22_allocate_lock = thread.allocate_lock
23_get_ident = thread.get_ident
Jeremy Hyltonb5fc7492000-06-01 01:17:17 +000024ThreadError = thread.error
Guido van Rossum7f5013a1998-04-09 22:01:42 +000025del thread
26
Guido van Rossum7f5013a1998-04-09 22:01:42 +000027
Jeffrey Yasskin105f3d42008-03-31 00:35:53 +000028# sys.exc_clear is used to work around the fact that except blocks
29# don't fully clear the exception until 3.0.
30warnings.filterwarnings('ignore', category=DeprecationWarning,
31 module='threading', message='sys.exc_clear')
32
33
Tim Peters59aba122003-07-01 20:01:55 +000034# Debug support (adapted from ihooks.py).
35# All the major classes here derive from _Verbose. We force that to
36# be a new-style class so that all the major classes here are new-style.
37# This helps debugging (type(instance) is more revealing for instances
38# of new-style classes).
Guido van Rossum7f5013a1998-04-09 22:01:42 +000039
Tim Peters0939fac2003-07-01 19:28:44 +000040_VERBOSE = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +000041
42if __debug__:
43
Tim Peters59aba122003-07-01 20:01:55 +000044 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000045
46 def __init__(self, verbose=None):
47 if verbose is None:
48 verbose = _VERBOSE
49 self.__verbose = verbose
50
51 def _note(self, format, *args):
52 if self.__verbose:
53 format = format % args
54 format = "%s: %s\n" % (
55 currentThread().getName(), format)
56 _sys.stderr.write(format)
57
58else:
59 # Disable this when using "python -O"
Tim Peters59aba122003-07-01 20:01:55 +000060 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000061 def __init__(self, verbose=None):
62 pass
63 def _note(self, *args):
64 pass
65
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000066# Support for profile and trace hooks
67
68_profile_hook = None
69_trace_hook = None
70
71def setprofile(func):
72 global _profile_hook
73 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000074
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000075def settrace(func):
76 global _trace_hook
77 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000078
79# Synchronization classes
80
81Lock = _allocate_lock
82
83def RLock(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +000084 return _RLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000085
86class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +000087
Guido van Rossum7f5013a1998-04-09 22:01:42 +000088 def __init__(self, verbose=None):
89 _Verbose.__init__(self, verbose)
90 self.__block = _allocate_lock()
91 self.__owner = None
92 self.__count = 0
93
94 def __repr__(self):
Nick Coghlanf8bbaa92007-07-31 13:38:01 +000095 owner = self.__owner
Guido van Rossum7f5013a1998-04-09 22:01:42 +000096 return "<%s(%s, %d)>" % (
97 self.__class__.__name__,
Nick Coghlanf8bbaa92007-07-31 13:38:01 +000098 owner and owner.getName(),
Guido van Rossum7f5013a1998-04-09 22:01:42 +000099 self.__count)
100
101 def acquire(self, blocking=1):
102 me = currentThread()
103 if self.__owner is me:
104 self.__count = self.__count + 1
105 if __debug__:
106 self._note("%s.acquire(%s): recursive success", self, blocking)
107 return 1
108 rc = self.__block.acquire(blocking)
109 if rc:
110 self.__owner = me
111 self.__count = 1
112 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000113 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000114 else:
115 if __debug__:
116 self._note("%s.acquire(%s): failure", self, blocking)
117 return rc
118
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000119 __enter__ = acquire
120
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000121 def release(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000122 if self.__owner is not currentThread():
123 raise RuntimeError("cannot release un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000124 self.__count = count = self.__count - 1
125 if not count:
126 self.__owner = None
127 self.__block.release()
128 if __debug__:
129 self._note("%s.release(): final release", self)
130 else:
131 if __debug__:
132 self._note("%s.release(): non-final release", self)
133
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000134 def __exit__(self, t, v, tb):
135 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000136
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000137 # Internal methods used by condition variables
138
139 def _acquire_restore(self, (count, owner)):
140 self.__block.acquire()
141 self.__count = count
142 self.__owner = owner
143 if __debug__:
144 self._note("%s._acquire_restore()", self)
145
146 def _release_save(self):
147 if __debug__:
148 self._note("%s._release_save()", self)
149 count = self.__count
150 self.__count = 0
151 owner = self.__owner
152 self.__owner = None
153 self.__block.release()
154 return (count, owner)
155
156 def _is_owned(self):
157 return self.__owner is currentThread()
158
159
160def Condition(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000161 return _Condition(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000162
163class _Condition(_Verbose):
164
165 def __init__(self, lock=None, verbose=None):
166 _Verbose.__init__(self, verbose)
167 if lock is None:
168 lock = RLock()
169 self.__lock = lock
170 # Export the lock's acquire() and release() methods
171 self.acquire = lock.acquire
172 self.release = lock.release
173 # If the lock defines _release_save() and/or _acquire_restore(),
174 # these override the default implementations (which just call
175 # release() and acquire() on the lock). Ditto for _is_owned().
176 try:
177 self._release_save = lock._release_save
178 except AttributeError:
179 pass
180 try:
181 self._acquire_restore = lock._acquire_restore
182 except AttributeError:
183 pass
184 try:
185 self._is_owned = lock._is_owned
186 except AttributeError:
187 pass
188 self.__waiters = []
189
Guido van Rossumda5b7012006-05-02 19:47:52 +0000190 def __enter__(self):
191 return self.__lock.__enter__()
192
193 def __exit__(self, *args):
194 return self.__lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000195
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000196 def __repr__(self):
197 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
198
199 def _release_save(self):
200 self.__lock.release() # No state to save
201
202 def _acquire_restore(self, x):
203 self.__lock.acquire() # Ignore saved state
204
205 def _is_owned(self):
Jeremy Hylton39c12bf2002-08-14 17:46:40 +0000206 # Return True if lock is owned by currentThread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000207 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000208 if self.__lock.acquire(0):
209 self.__lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000210 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000211 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000212 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000213
214 def wait(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000215 if not self._is_owned():
216 raise RuntimeError("cannot wait on un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000217 waiter = _allocate_lock()
218 waiter.acquire()
219 self.__waiters.append(waiter)
220 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000221 try: # restore state no matter what (e.g., KeyboardInterrupt)
222 if timeout is None:
223 waiter.acquire()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000224 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000225 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000226 else:
Tim Petersa6a4f272001-08-12 00:41:33 +0000227 # Balancing act: We can't afford a pure busy loop, so we
228 # have to sleep; but if we sleep the whole timeout time,
229 # we'll be unresponsive. The scheme here sleeps very
230 # little at first, longer as time goes on, but never longer
231 # than 20 times per second (or the timeout time remaining).
Tim Petersc951bf92001-04-02 20:15:57 +0000232 endtime = _time() + timeout
Tim Petersa6a4f272001-08-12 00:41:33 +0000233 delay = 0.0005 # 500 us -> initial delay of 1 ms
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000234 while True:
Tim Petersc951bf92001-04-02 20:15:57 +0000235 gotit = waiter.acquire(0)
Tim Petersa6a4f272001-08-12 00:41:33 +0000236 if gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000237 break
Tim Petersa6a4f272001-08-12 00:41:33 +0000238 remaining = endtime - _time()
239 if remaining <= 0:
240 break
241 delay = min(delay * 2, remaining, .05)
Tim Petersc951bf92001-04-02 20:15:57 +0000242 _sleep(delay)
Tim Petersc951bf92001-04-02 20:15:57 +0000243 if not gotit:
244 if __debug__:
245 self._note("%s.wait(%s): timed out", self, timeout)
246 try:
247 self.__waiters.remove(waiter)
248 except ValueError:
249 pass
250 else:
251 if __debug__:
252 self._note("%s.wait(%s): got it", self, timeout)
253 finally:
254 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000255
256 def notify(self, n=1):
Collin Winter50b79ce2007-06-06 00:17:35 +0000257 if not self._is_owned():
258 raise RuntimeError("cannot notify on un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000259 __waiters = self.__waiters
260 waiters = __waiters[:n]
261 if not waiters:
262 if __debug__:
263 self._note("%s.notify(): no waiters", self)
264 return
265 self._note("%s.notify(): notifying %d waiter%s", self, n,
266 n!=1 and "s" or "")
267 for waiter in waiters:
268 waiter.release()
269 try:
270 __waiters.remove(waiter)
271 except ValueError:
272 pass
273
274 def notifyAll(self):
275 self.notify(len(self.__waiters))
276
277
278def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000279 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000280
281class _Semaphore(_Verbose):
282
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000283 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000284
285 def __init__(self, value=1, verbose=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000286 if value < 0:
287 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000288 _Verbose.__init__(self, verbose)
289 self.__cond = Condition(Lock())
290 self.__value = value
291
292 def acquire(self, blocking=1):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000293 rc = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000294 self.__cond.acquire()
295 while self.__value == 0:
296 if not blocking:
297 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000298 if __debug__:
299 self._note("%s.acquire(%s): blocked waiting, value=%s",
300 self, blocking, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000301 self.__cond.wait()
302 else:
303 self.__value = self.__value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000304 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000305 self._note("%s.acquire: success, value=%s",
306 self, self.__value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000307 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000308 self.__cond.release()
309 return rc
310
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000311 __enter__ = acquire
312
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000313 def release(self):
314 self.__cond.acquire()
315 self.__value = self.__value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000316 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000317 self._note("%s.release: success, value=%s",
318 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000319 self.__cond.notify()
320 self.__cond.release()
321
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000322 def __exit__(self, t, v, tb):
323 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000324
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000325
Skip Montanaroe428bb72001-08-20 20:27:58 +0000326def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000327 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000328
329class _BoundedSemaphore(_Semaphore):
330 """Semaphore that checks that # releases is <= # acquires"""
331 def __init__(self, value=1, verbose=None):
332 _Semaphore.__init__(self, value, verbose)
333 self._initial_value = value
334
335 def release(self):
336 if self._Semaphore__value >= self._initial_value:
337 raise ValueError, "Semaphore released too many times"
338 return _Semaphore.release(self)
339
340
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000341def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000342 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000343
344class _Event(_Verbose):
345
346 # After Tim Peters' event class (without is_posted())
347
348 def __init__(self, verbose=None):
349 _Verbose.__init__(self, verbose)
350 self.__cond = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000351 self.__flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000352
353 def isSet(self):
354 return self.__flag
355
356 def set(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000357 self.__cond.acquire()
358 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000359 self.__flag = True
360 self.__cond.notifyAll()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000361 finally:
362 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000363
364 def clear(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000365 self.__cond.acquire()
366 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000367 self.__flag = False
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000368 finally:
369 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000370
371 def wait(self, timeout=None):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000372 self.__cond.acquire()
373 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000374 if not self.__flag:
375 self.__cond.wait(timeout)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000376 finally:
377 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000378
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000379# Helper to generate new thread names
380_counter = 0
381def _newname(template="Thread-%d"):
382 global _counter
383 _counter = _counter + 1
384 return template % _counter
385
386# Active thread administration
387_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000388_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000389_limbo = {}
390
391
392# Main class for threads
393
394class Thread(_Verbose):
395
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000396 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000397 # Need to store a reference to sys.exc_info for printing
398 # out exceptions when a thread tries to use a global var. during interp.
399 # shutdown and thus raises an exception about trying to perform some
400 # operation on/with a NoneType
401 __exc_info = _sys.exc_info
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000402 # Keep sys.exc_clear too to clear the exception just before
403 # allowing .join() to return.
404 __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000405
406 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000407 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000408 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000409 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000410 if kwargs is None:
411 kwargs = {}
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000412 self.__target = target
413 self.__name = str(name or _newname())
414 self.__args = args
415 self.__kwargs = kwargs
416 self.__daemonic = self._set_daemon()
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000417 self.__ident = None
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000418 self.__started = Event()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000419 self.__stopped = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000420 self.__block = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000421 self.__initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000422 # sys.stderr is not stored in the class like
423 # sys.exc_info since it can be changed between instances
424 self.__stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000425
426 def _set_daemon(self):
427 # Overridden in _MainThread and _DummyThread
428 return currentThread().isDaemon()
429
430 def __repr__(self):
431 assert self.__initialized, "Thread.__init__() was not called"
432 status = "initial"
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000433 if self.__started.isSet():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000434 status = "started"
435 if self.__stopped:
436 status = "stopped"
437 if self.__daemonic:
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000438 status += " daemon"
439 if self.__ident is not None:
440 status += " %s" % self.__ident
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000441 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
442
443 def start(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000444 if not self.__initialized:
445 raise RuntimeError("thread.__init__() not called")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000446 if self.__started.isSet():
Collin Winter50b79ce2007-06-06 00:17:35 +0000447 raise RuntimeError("thread already started")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000448 if __debug__:
449 self._note("%s.start(): starting thread", self)
450 _active_limbo_lock.acquire()
451 _limbo[self] = self
452 _active_limbo_lock.release()
453 _start_new_thread(self.__bootstrap, ())
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000454 self.__started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000455
456 def run(self):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000457 try:
458 if self.__target:
459 self.__target(*self.__args, **self.__kwargs)
460 finally:
461 # Avoid a refcycle if the thread is running a function with
462 # an argument that has a member that points to the thread.
463 del self.__target, self.__args, self.__kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000464
465 def __bootstrap(self):
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000466 # Wrapper around the real bootstrap code that ignores
467 # exceptions during interpreter cleanup. Those typically
468 # happen when a daemon thread wakes up at an unfortunate
469 # moment, finds the world around it destroyed, and raises some
470 # random exception *** while trying to report the exception in
471 # __bootstrap_inner() below ***. Those random exceptions
472 # don't help anybody, and they confuse users, so we suppress
473 # them. We suppress them only when it appears that the world
474 # indeed has already been destroyed, so that exceptions in
475 # __bootstrap_inner() during normal business hours are properly
476 # reported. Also, we only suppress them for daemonic threads;
477 # if a non-daemonic encounters this, something else is wrong.
478 try:
479 self.__bootstrap_inner()
480 except:
481 if self.__daemonic and _sys is None:
482 return
483 raise
484
485 def __bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000486 try:
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000487 self.__ident = _get_ident()
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000488 self.__started.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000489 _active_limbo_lock.acquire()
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000490 _active[self.__ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000491 del _limbo[self]
492 _active_limbo_lock.release()
493 if __debug__:
494 self._note("%s.__bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000495
496 if _trace_hook:
497 self._note("%s.__bootstrap(): registering trace hook", self)
498 _sys.settrace(_trace_hook)
499 if _profile_hook:
500 self._note("%s.__bootstrap(): registering profile hook", self)
501 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000502
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000503 try:
504 self.run()
505 except SystemExit:
506 if __debug__:
507 self._note("%s.__bootstrap(): raised SystemExit", self)
508 except:
509 if __debug__:
510 self._note("%s.__bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000511 # If sys.stderr is no more (most likely from interpreter
512 # shutdown) use self.__stderr. Otherwise still use sys (as in
513 # _sys) in case sys.stderr was redefined since the creation of
514 # self.
515 if _sys:
516 _sys.stderr.write("Exception in thread %s:\n%s\n" %
517 (self.getName(), _format_exc()))
518 else:
519 # Do the best job possible w/o a huge amt. of code to
520 # approximate a traceback (code ideas from
521 # Lib/traceback.py)
522 exc_type, exc_value, exc_tb = self.__exc_info()
523 try:
524 print>>self.__stderr, (
525 "Exception in thread " + self.getName() +
526 " (most likely raised during interpreter shutdown):")
527 print>>self.__stderr, (
528 "Traceback (most recent call last):")
529 while exc_tb:
530 print>>self.__stderr, (
531 ' File "%s", line %s, in %s' %
532 (exc_tb.tb_frame.f_code.co_filename,
533 exc_tb.tb_lineno,
534 exc_tb.tb_frame.f_code.co_name))
535 exc_tb = exc_tb.tb_next
536 print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
537 # Make sure that exc_tb gets deleted since it is a memory
538 # hog; deleting everything else is just for thoroughness
539 finally:
540 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000541 else:
542 if __debug__:
543 self._note("%s.__bootstrap(): normal return", self)
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000544 finally:
545 # Prevent a race in
546 # test_threading.test_no_refcycle_through_target when
547 # the exception keeps the target alive past when we
548 # assert that it's dead.
Amaury Forgeot d'Arc504a48f2008-03-29 01:41:08 +0000549 self.__exc_clear()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000550 finally:
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000551 with _active_limbo_lock:
552 self.__stop()
553 try:
554 # We don't call self.__delete() because it also
555 # grabs _active_limbo_lock.
556 del _active[_get_ident()]
557 except:
558 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000559
560 def __stop(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000561 self.__block.acquire()
562 self.__stopped = True
563 self.__block.notifyAll()
564 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000565
566 def __delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000567 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000568
Tim Peters21429932004-07-21 03:36:52 +0000569 # Notes about running with dummy_thread:
570 #
571 # Must take care to not raise an exception if dummy_thread is being
572 # used (and thus this module is being used as an instance of
573 # dummy_threading). dummy_thread.get_ident() always returns -1 since
574 # there is only one thread if dummy_thread is being used. Thus
575 # len(_active) is always <= 1 here, and any Thread instance created
576 # overwrites the (if any) thread currently registered in _active.
577 #
578 # An instance of _MainThread is always created by 'threading'. This
579 # gets overwritten the instant an instance of Thread is created; both
580 # threads return -1 from dummy_thread.get_ident() and thus have the
581 # same key in the dict. So when the _MainThread instance created by
582 # 'threading' tries to clean itself up when atexit calls this method
583 # it gets a KeyError if another Thread instance was created.
584 #
585 # This all means that KeyError from trying to delete something from
586 # _active if dummy_threading is being used is a red herring. But
587 # since it isn't if dummy_threading is *not* being used then don't
588 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000589
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000590 try:
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000591 with _active_limbo_lock:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000592 del _active[_get_ident()]
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000593 # There must not be any python code between the previous line
594 # and after the lock is released. Otherwise a tracing function
595 # could try to acquire the lock again in the same thread, (in
596 # currentThread()), and would block.
597 except KeyError:
598 if 'dummy_threading' not in _sys.modules:
599 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000600
601 def join(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000602 if not self.__initialized:
603 raise RuntimeError("Thread.__init__() not called")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000604 if not self.__started.isSet():
Collin Winter50b79ce2007-06-06 00:17:35 +0000605 raise RuntimeError("cannot join thread before it is started")
606 if self is currentThread():
607 raise RuntimeError("cannot join current thread")
608
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000609 if __debug__:
610 if not self.__stopped:
611 self._note("%s.join(): waiting until thread stops", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000612 self.__block.acquire()
613 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000614 if timeout is None:
615 while not self.__stopped:
616 self.__block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000617 if __debug__:
618 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000619 else:
620 deadline = _time() + timeout
621 while not self.__stopped:
622 delay = deadline - _time()
623 if delay <= 0:
624 if __debug__:
625 self._note("%s.join(): timed out", self)
626 break
627 self.__block.wait(delay)
628 else:
629 if __debug__:
630 self._note("%s.join(): thread stopped", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000631 finally:
632 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000633
634 def getName(self):
635 assert self.__initialized, "Thread.__init__() not called"
636 return self.__name
637
638 def setName(self, name):
639 assert self.__initialized, "Thread.__init__() not called"
640 self.__name = str(name)
641
Gregory P. Smith8856dda2008-06-01 23:48:47 +0000642 def getIdent(self):
643 assert self.__initialized, "Thread.__init__() not called"
644 return self.__ident
645
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000646 def isAlive(self):
647 assert self.__initialized, "Thread.__init__() not called"
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000648 return self.__started.isSet() and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000649
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000650 def isDaemon(self):
651 assert self.__initialized, "Thread.__init__() not called"
652 return self.__daemonic
653
654 def setDaemon(self, daemonic):
Collin Winter50b79ce2007-06-06 00:17:35 +0000655 if not self.__initialized:
656 raise RuntimeError("Thread.__init__() not called")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000657 if self.__started.isSet():
Collin Winter50b79ce2007-06-06 00:17:35 +0000658 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000659 self.__daemonic = daemonic
660
Martin v. Löwis44f86962001-09-05 13:44:54 +0000661# The timer class was contributed by Itamar Shtull-Trauring
662
663def Timer(*args, **kwargs):
664 return _Timer(*args, **kwargs)
665
666class _Timer(Thread):
667 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000668
Martin v. Löwis44f86962001-09-05 13:44:54 +0000669 t = Timer(30.0, f, args=[], kwargs={})
670 t.start()
671 t.cancel() # stop the timer's action if it's still waiting
672 """
Tim Petersb64bec32001-09-18 02:26:39 +0000673
Martin v. Löwis44f86962001-09-05 13:44:54 +0000674 def __init__(self, interval, function, args=[], kwargs={}):
675 Thread.__init__(self)
676 self.interval = interval
677 self.function = function
678 self.args = args
679 self.kwargs = kwargs
680 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000681
Martin v. Löwis44f86962001-09-05 13:44:54 +0000682 def cancel(self):
683 """Stop the timer if it hasn't finished yet"""
684 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000685
Martin v. Löwis44f86962001-09-05 13:44:54 +0000686 def run(self):
687 self.finished.wait(self.interval)
688 if not self.finished.isSet():
689 self.function(*self.args, **self.kwargs)
690 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000691
692# Special thread class to represent the main thread
693# This is garbage collected through an exit handler
694
695class _MainThread(Thread):
696
697 def __init__(self):
698 Thread.__init__(self, name="MainThread")
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000699 self._Thread__started.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000700 _active_limbo_lock.acquire()
701 _active[_get_ident()] = self
702 _active_limbo_lock.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000703
704 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000705 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000706
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000707 def _exitfunc(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000708 self._Thread__stop()
709 t = _pickSomeNonDaemonThread()
710 if t:
711 if __debug__:
712 self._note("%s: waiting for other threads", self)
713 while t:
714 t.join()
715 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000716 if __debug__:
717 self._note("%s: exiting", self)
718 self._Thread__delete()
719
720def _pickSomeNonDaemonThread():
721 for t in enumerate():
722 if not t.isDaemon() and t.isAlive():
723 return t
724 return None
725
726
727# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000728# These aren't garbage collected when they die, nor can they be waited for.
729# If they invoke anything in threading.py that calls currentThread(), they
730# leave an entry in the _active dict forever after.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000731# Their purpose is to return *something* from currentThread().
732# They are marked as daemon threads so we won't wait for them
733# when we exit (conform previous semantics).
734
735class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000736
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000737 def __init__(self):
738 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000739
740 # Thread.__block consumes an OS-level locking primitive, which
741 # can never be used by a _DummyThread. Since a _DummyThread
742 # instance is immortal, that's bad, so release this resource.
Brett Cannone6539c42005-01-08 02:43:53 +0000743 del self._Thread__block
Tim Peters711906e2005-01-08 07:30:42 +0000744
Jeffrey Yasskin69e13092008-02-28 06:09:19 +0000745 self._Thread__started.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000746 _active_limbo_lock.acquire()
747 _active[_get_ident()] = self
748 _active_limbo_lock.release()
749
750 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000751 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000752
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000753 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000754 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000755
756
757# Global API functions
758
759def currentThread():
760 try:
761 return _active[_get_ident()]
762 except KeyError:
Guido van Rossum5080b332000-12-15 20:08:39 +0000763 ##print "currentThread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000764 return _DummyThread()
765
766def activeCount():
767 _active_limbo_lock.acquire()
768 count = len(_active) + len(_limbo)
769 _active_limbo_lock.release()
770 return count
771
772def enumerate():
773 _active_limbo_lock.acquire()
774 active = _active.values() + _limbo.values()
775 _active_limbo_lock.release()
776 return active
777
Andrew MacIntyre92913322006-06-13 15:04:24 +0000778from thread import stack_size
779
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000780# Create the main thread object,
781# and make it available for the interpreter
782# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000783
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000784_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000785
Jim Fultond15dc062004-07-14 19:11:50 +0000786# get thread-local implementation, either from the thread
787# module, or from the python fallback
788
789try:
790 from thread import _local as local
791except ImportError:
792 from _threading_local import local
793
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000794
795# Self-test code
796
797def _test():
798
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000799 class BoundedQueue(_Verbose):
800
801 def __init__(self, limit):
802 _Verbose.__init__(self)
803 self.mon = RLock()
804 self.rc = Condition(self.mon)
805 self.wc = Condition(self.mon)
806 self.limit = limit
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000807 self.queue = deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000808
809 def put(self, item):
810 self.mon.acquire()
811 while len(self.queue) >= self.limit:
812 self._note("put(%s): queue full", item)
813 self.wc.wait()
814 self.queue.append(item)
815 self._note("put(%s): appended, length now %d",
816 item, len(self.queue))
817 self.rc.notify()
818 self.mon.release()
819
820 def get(self):
821 self.mon.acquire()
822 while not self.queue:
823 self._note("get(): queue empty")
824 self.rc.wait()
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000825 item = self.queue.popleft()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000826 self._note("get(): got %s, %d left", item, len(self.queue))
827 self.wc.notify()
828 self.mon.release()
829 return item
830
831 class ProducerThread(Thread):
832
833 def __init__(self, queue, quota):
834 Thread.__init__(self, name="Producer")
835 self.queue = queue
836 self.quota = quota
837
838 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000839 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000840 counter = 0
841 while counter < self.quota:
842 counter = counter + 1
843 self.queue.put("%s.%d" % (self.getName(), counter))
844 _sleep(random() * 0.00001)
845
846
847 class ConsumerThread(Thread):
848
849 def __init__(self, queue, count):
850 Thread.__init__(self, name="Consumer")
851 self.queue = queue
852 self.count = count
853
854 def run(self):
855 while self.count > 0:
856 item = self.queue.get()
857 print item
858 self.count = self.count - 1
859
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000860 NP = 3
861 QL = 4
862 NI = 5
863
864 Q = BoundedQueue(QL)
865 P = []
866 for i in range(NP):
867 t = ProducerThread(Q, NI)
868 t.setName("Producer-%d" % (i+1))
869 P.append(t)
870 C = ConsumerThread(Q, NI*NP)
871 for t in P:
872 t.start()
873 _sleep(0.000001)
874 C.start()
875 for t in P:
876 t.join()
877 C.join()
878
879if __name__ == '__main__':
880 _test()