blob: 005d40c63ed1fc63ea8eca5e019a4a5692483ef0 [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
Fred Drakea8725952002-12-30 23:32:50 +000011from time import time as _time, sleep as _sleep
Neil Schemenauerf607fc52003-11-05 23:03:00 +000012from traceback import format_exc as _format_exc
Raymond Hettinger756b3f32004-01-29 06:37:52 +000013from collections import deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000014
15# Rename some stuff so "from threading import *" is safe
Guido van Rossumc262a1f2002-12-30 21:59:55 +000016__all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event',
Tim Peters685e6972003-06-29 16:50:06 +000017 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
Andrew MacIntyre92913322006-06-13 15:04:24 +000018 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000019
Guido van Rossum7f5013a1998-04-09 22:01:42 +000020_start_new_thread = thread.start_new_thread
21_allocate_lock = thread.allocate_lock
22_get_ident = thread.get_ident
Jeremy Hyltonb5fc7492000-06-01 01:17:17 +000023ThreadError = thread.error
Guido van Rossum7f5013a1998-04-09 22:01:42 +000024del thread
25
Guido van Rossum7f5013a1998-04-09 22:01:42 +000026
Tim Peters59aba122003-07-01 20:01:55 +000027# Debug support (adapted from ihooks.py).
28# All the major classes here derive from _Verbose. We force that to
29# be a new-style class so that all the major classes here are new-style.
30# This helps debugging (type(instance) is more revealing for instances
31# of new-style classes).
Guido van Rossum7f5013a1998-04-09 22:01:42 +000032
Tim Peters0939fac2003-07-01 19:28:44 +000033_VERBOSE = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +000034
35if __debug__:
36
Tim Peters59aba122003-07-01 20:01:55 +000037 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000038
39 def __init__(self, verbose=None):
40 if verbose is None:
41 verbose = _VERBOSE
42 self.__verbose = verbose
43
44 def _note(self, format, *args):
45 if self.__verbose:
46 format = format % args
47 format = "%s: %s\n" % (
48 currentThread().getName(), format)
49 _sys.stderr.write(format)
50
51else:
52 # Disable this when using "python -O"
Tim Peters59aba122003-07-01 20:01:55 +000053 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000054 def __init__(self, verbose=None):
55 pass
56 def _note(self, *args):
57 pass
58
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000059# Support for profile and trace hooks
60
61_profile_hook = None
62_trace_hook = None
63
64def setprofile(func):
65 global _profile_hook
66 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000067
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000068def settrace(func):
69 global _trace_hook
70 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000071
72# Synchronization classes
73
74Lock = _allocate_lock
75
76def RLock(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +000077 return _RLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000078
79class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +000080
Guido van Rossum7f5013a1998-04-09 22:01:42 +000081 def __init__(self, verbose=None):
82 _Verbose.__init__(self, verbose)
83 self.__block = _allocate_lock()
84 self.__owner = None
85 self.__count = 0
86
87 def __repr__(self):
Nick Coghlanf8bbaa92007-07-31 13:38:01 +000088 owner = self.__owner
Guido van Rossum7f5013a1998-04-09 22:01:42 +000089 return "<%s(%s, %d)>" % (
90 self.__class__.__name__,
Nick Coghlanf8bbaa92007-07-31 13:38:01 +000091 owner and owner.getName(),
Guido van Rossum7f5013a1998-04-09 22:01:42 +000092 self.__count)
93
94 def acquire(self, blocking=1):
95 me = currentThread()
96 if self.__owner is me:
97 self.__count = self.__count + 1
98 if __debug__:
99 self._note("%s.acquire(%s): recursive success", self, blocking)
100 return 1
101 rc = self.__block.acquire(blocking)
102 if rc:
103 self.__owner = me
104 self.__count = 1
105 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000106 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000107 else:
108 if __debug__:
109 self._note("%s.acquire(%s): failure", self, blocking)
110 return rc
111
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000112 __enter__ = acquire
113
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000114 def release(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000115 if self.__owner is not currentThread():
116 raise RuntimeError("cannot release un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000117 self.__count = count = self.__count - 1
118 if not count:
119 self.__owner = None
120 self.__block.release()
121 if __debug__:
122 self._note("%s.release(): final release", self)
123 else:
124 if __debug__:
125 self._note("%s.release(): non-final release", self)
126
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000127 def __exit__(self, t, v, tb):
128 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000129
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000130 # Internal methods used by condition variables
131
132 def _acquire_restore(self, (count, owner)):
133 self.__block.acquire()
134 self.__count = count
135 self.__owner = owner
136 if __debug__:
137 self._note("%s._acquire_restore()", self)
138
139 def _release_save(self):
140 if __debug__:
141 self._note("%s._release_save()", self)
142 count = self.__count
143 self.__count = 0
144 owner = self.__owner
145 self.__owner = None
146 self.__block.release()
147 return (count, owner)
148
149 def _is_owned(self):
150 return self.__owner is currentThread()
151
152
153def Condition(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000154 return _Condition(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000155
156class _Condition(_Verbose):
157
158 def __init__(self, lock=None, verbose=None):
159 _Verbose.__init__(self, verbose)
160 if lock is None:
161 lock = RLock()
162 self.__lock = lock
163 # Export the lock's acquire() and release() methods
164 self.acquire = lock.acquire
165 self.release = lock.release
166 # If the lock defines _release_save() and/or _acquire_restore(),
167 # these override the default implementations (which just call
168 # release() and acquire() on the lock). Ditto for _is_owned().
169 try:
170 self._release_save = lock._release_save
171 except AttributeError:
172 pass
173 try:
174 self._acquire_restore = lock._acquire_restore
175 except AttributeError:
176 pass
177 try:
178 self._is_owned = lock._is_owned
179 except AttributeError:
180 pass
181 self.__waiters = []
182
Guido van Rossumda5b7012006-05-02 19:47:52 +0000183 def __enter__(self):
184 return self.__lock.__enter__()
185
186 def __exit__(self, *args):
187 return self.__lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000188
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000189 def __repr__(self):
190 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
191
192 def _release_save(self):
193 self.__lock.release() # No state to save
194
195 def _acquire_restore(self, x):
196 self.__lock.acquire() # Ignore saved state
197
198 def _is_owned(self):
Jeremy Hylton39c12bf2002-08-14 17:46:40 +0000199 # Return True if lock is owned by currentThread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000200 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000201 if self.__lock.acquire(0):
202 self.__lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000203 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000204 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000205 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000206
207 def wait(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000208 if not self._is_owned():
209 raise RuntimeError("cannot wait on un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000210 waiter = _allocate_lock()
211 waiter.acquire()
212 self.__waiters.append(waiter)
213 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000214 try: # restore state no matter what (e.g., KeyboardInterrupt)
215 if timeout is None:
216 waiter.acquire()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000217 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000218 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000219 else:
Tim Petersa6a4f272001-08-12 00:41:33 +0000220 # Balancing act: We can't afford a pure busy loop, so we
221 # have to sleep; but if we sleep the whole timeout time,
222 # we'll be unresponsive. The scheme here sleeps very
223 # little at first, longer as time goes on, but never longer
224 # than 20 times per second (or the timeout time remaining).
Tim Petersc951bf92001-04-02 20:15:57 +0000225 endtime = _time() + timeout
Tim Petersa6a4f272001-08-12 00:41:33 +0000226 delay = 0.0005 # 500 us -> initial delay of 1 ms
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000227 while True:
Tim Petersc951bf92001-04-02 20:15:57 +0000228 gotit = waiter.acquire(0)
Tim Petersa6a4f272001-08-12 00:41:33 +0000229 if gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000230 break
Tim Petersa6a4f272001-08-12 00:41:33 +0000231 remaining = endtime - _time()
232 if remaining <= 0:
233 break
234 delay = min(delay * 2, remaining, .05)
Tim Petersc951bf92001-04-02 20:15:57 +0000235 _sleep(delay)
Tim Petersc951bf92001-04-02 20:15:57 +0000236 if not gotit:
237 if __debug__:
238 self._note("%s.wait(%s): timed out", self, timeout)
239 try:
240 self.__waiters.remove(waiter)
241 except ValueError:
242 pass
243 else:
244 if __debug__:
245 self._note("%s.wait(%s): got it", self, timeout)
246 finally:
247 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000248
249 def notify(self, n=1):
Collin Winter50b79ce2007-06-06 00:17:35 +0000250 if not self._is_owned():
251 raise RuntimeError("cannot notify on un-aquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000252 __waiters = self.__waiters
253 waiters = __waiters[:n]
254 if not waiters:
255 if __debug__:
256 self._note("%s.notify(): no waiters", self)
257 return
258 self._note("%s.notify(): notifying %d waiter%s", self, n,
259 n!=1 and "s" or "")
260 for waiter in waiters:
261 waiter.release()
262 try:
263 __waiters.remove(waiter)
264 except ValueError:
265 pass
266
267 def notifyAll(self):
268 self.notify(len(self.__waiters))
269
270
271def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000272 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000273
274class _Semaphore(_Verbose):
275
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000276 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000277
278 def __init__(self, value=1, verbose=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000279 if value < 0:
280 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000281 _Verbose.__init__(self, verbose)
282 self.__cond = Condition(Lock())
283 self.__value = value
284
285 def acquire(self, blocking=1):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000286 rc = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000287 self.__cond.acquire()
288 while self.__value == 0:
289 if not blocking:
290 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000291 if __debug__:
292 self._note("%s.acquire(%s): blocked waiting, value=%s",
293 self, blocking, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000294 self.__cond.wait()
295 else:
296 self.__value = self.__value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000297 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000298 self._note("%s.acquire: success, value=%s",
299 self, self.__value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000300 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000301 self.__cond.release()
302 return rc
303
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000304 __enter__ = acquire
305
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000306 def release(self):
307 self.__cond.acquire()
308 self.__value = self.__value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000309 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000310 self._note("%s.release: success, value=%s",
311 self, self.__value)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000312 self.__cond.notify()
313 self.__cond.release()
314
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000315 def __exit__(self, t, v, tb):
316 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000317
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000318
Skip Montanaroe428bb72001-08-20 20:27:58 +0000319def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000320 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000321
322class _BoundedSemaphore(_Semaphore):
323 """Semaphore that checks that # releases is <= # acquires"""
324 def __init__(self, value=1, verbose=None):
325 _Semaphore.__init__(self, value, verbose)
326 self._initial_value = value
327
328 def release(self):
329 if self._Semaphore__value >= self._initial_value:
330 raise ValueError, "Semaphore released too many times"
331 return _Semaphore.release(self)
332
333
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000334def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000335 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000336
337class _Event(_Verbose):
338
339 # After Tim Peters' event class (without is_posted())
340
341 def __init__(self, verbose=None):
342 _Verbose.__init__(self, verbose)
343 self.__cond = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000344 self.__flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000345
346 def isSet(self):
347 return self.__flag
348
349 def set(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000350 self.__cond.acquire()
351 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000352 self.__flag = True
353 self.__cond.notifyAll()
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000354 finally:
355 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000356
357 def clear(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000358 self.__cond.acquire()
359 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000360 self.__flag = False
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000361 finally:
362 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000363
364 def wait(self, timeout=None):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000365 self.__cond.acquire()
366 try:
Guido van Rossum21b60142002-11-21 21:08:39 +0000367 if not self.__flag:
368 self.__cond.wait(timeout)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000369 finally:
370 self.__cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000371
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000372# Helper to generate new thread names
373_counter = 0
374def _newname(template="Thread-%d"):
375 global _counter
376 _counter = _counter + 1
377 return template % _counter
378
379# Active thread administration
380_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000381_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000382_limbo = {}
383
384
385# Main class for threads
386
387class Thread(_Verbose):
388
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000389 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000390 # Need to store a reference to sys.exc_info for printing
391 # out exceptions when a thread tries to use a global var. during interp.
392 # shutdown and thus raises an exception about trying to perform some
393 # operation on/with a NoneType
394 __exc_info = _sys.exc_info
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000395
396 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000397 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000398 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000399 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000400 if kwargs is None:
401 kwargs = {}
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000402 self.__target = target
403 self.__name = str(name or _newname())
404 self.__args = args
405 self.__kwargs = kwargs
406 self.__daemonic = self._set_daemon()
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000407 self.__started = False
408 self.__stopped = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000409 self.__block = Condition(Lock())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000410 self.__initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000411 # sys.stderr is not stored in the class like
412 # sys.exc_info since it can be changed between instances
413 self.__stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000414
415 def _set_daemon(self):
416 # Overridden in _MainThread and _DummyThread
417 return currentThread().isDaemon()
418
419 def __repr__(self):
420 assert self.__initialized, "Thread.__init__() was not called"
421 status = "initial"
422 if self.__started:
423 status = "started"
424 if self.__stopped:
425 status = "stopped"
426 if self.__daemonic:
427 status = status + " daemon"
428 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
429
430 def start(self):
Collin Winter50b79ce2007-06-06 00:17:35 +0000431 if not self.__initialized:
432 raise RuntimeError("thread.__init__() not called")
433 if self.__started:
434 raise RuntimeError("thread already started")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000435 if __debug__:
436 self._note("%s.start(): starting thread", self)
437 _active_limbo_lock.acquire()
438 _limbo[self] = self
439 _active_limbo_lock.release()
440 _start_new_thread(self.__bootstrap, ())
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000441 self.__started = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000442 _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
443
444 def run(self):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000445 try:
446 if self.__target:
447 self.__target(*self.__args, **self.__kwargs)
448 finally:
449 # Avoid a refcycle if the thread is running a function with
450 # an argument that has a member that points to the thread.
451 del self.__target, self.__args, self.__kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000452
453 def __bootstrap(self):
Guido van Rossum54ec61e2007-08-20 15:18:04 +0000454 # Wrapper around the real bootstrap code that ignores
455 # exceptions during interpreter cleanup. Those typically
456 # happen when a daemon thread wakes up at an unfortunate
457 # moment, finds the world around it destroyed, and raises some
458 # random exception *** while trying to report the exception in
459 # __bootstrap_inner() below ***. Those random exceptions
460 # don't help anybody, and they confuse users, so we suppress
461 # them. We suppress them only when it appears that the world
462 # indeed has already been destroyed, so that exceptions in
463 # __bootstrap_inner() during normal business hours are properly
464 # reported. Also, we only suppress them for daemonic threads;
465 # if a non-daemonic encounters this, something else is wrong.
466 try:
467 self.__bootstrap_inner()
468 except:
469 if self.__daemonic and _sys is None:
470 return
471 raise
472
473 def __bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000474 try:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000475 self.__started = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000476 _active_limbo_lock.acquire()
477 _active[_get_ident()] = self
478 del _limbo[self]
479 _active_limbo_lock.release()
480 if __debug__:
481 self._note("%s.__bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000482
483 if _trace_hook:
484 self._note("%s.__bootstrap(): registering trace hook", self)
485 _sys.settrace(_trace_hook)
486 if _profile_hook:
487 self._note("%s.__bootstrap(): registering profile hook", self)
488 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000489
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000490 try:
491 self.run()
492 except SystemExit:
493 if __debug__:
494 self._note("%s.__bootstrap(): raised SystemExit", self)
495 except:
496 if __debug__:
497 self._note("%s.__bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000498 # If sys.stderr is no more (most likely from interpreter
499 # shutdown) use self.__stderr. Otherwise still use sys (as in
500 # _sys) in case sys.stderr was redefined since the creation of
501 # self.
502 if _sys:
503 _sys.stderr.write("Exception in thread %s:\n%s\n" %
504 (self.getName(), _format_exc()))
505 else:
506 # Do the best job possible w/o a huge amt. of code to
507 # approximate a traceback (code ideas from
508 # Lib/traceback.py)
509 exc_type, exc_value, exc_tb = self.__exc_info()
510 try:
511 print>>self.__stderr, (
512 "Exception in thread " + self.getName() +
513 " (most likely raised during interpreter shutdown):")
514 print>>self.__stderr, (
515 "Traceback (most recent call last):")
516 while exc_tb:
517 print>>self.__stderr, (
518 ' File "%s", line %s, in %s' %
519 (exc_tb.tb_frame.f_code.co_filename,
520 exc_tb.tb_lineno,
521 exc_tb.tb_frame.f_code.co_name))
522 exc_tb = exc_tb.tb_next
523 print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
524 # Make sure that exc_tb gets deleted since it is a memory
525 # hog; deleting everything else is just for thoroughness
526 finally:
527 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000528 else:
529 if __debug__:
530 self._note("%s.__bootstrap(): normal return", self)
531 finally:
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000532 with _active_limbo_lock:
533 self.__stop()
534 try:
535 # We don't call self.__delete() because it also
536 # grabs _active_limbo_lock.
537 del _active[_get_ident()]
538 except:
539 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000540
541 def __stop(self):
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000542 self.__block.acquire()
543 self.__stopped = True
544 self.__block.notifyAll()
545 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000546
547 def __delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000548 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000549
Tim Peters21429932004-07-21 03:36:52 +0000550 # Notes about running with dummy_thread:
551 #
552 # Must take care to not raise an exception if dummy_thread is being
553 # used (and thus this module is being used as an instance of
554 # dummy_threading). dummy_thread.get_ident() always returns -1 since
555 # there is only one thread if dummy_thread is being used. Thus
556 # len(_active) is always <= 1 here, and any Thread instance created
557 # overwrites the (if any) thread currently registered in _active.
558 #
559 # An instance of _MainThread is always created by 'threading'. This
560 # gets overwritten the instant an instance of Thread is created; both
561 # threads return -1 from dummy_thread.get_ident() and thus have the
562 # same key in the dict. So when the _MainThread instance created by
563 # 'threading' tries to clean itself up when atexit calls this method
564 # it gets a KeyError if another Thread instance was created.
565 #
566 # This all means that KeyError from trying to delete something from
567 # _active if dummy_threading is being used is a red herring. But
568 # since it isn't if dummy_threading is *not* being used then don't
569 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000570
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000571 _active_limbo_lock.acquire()
572 try:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000573 try:
574 del _active[_get_ident()]
575 except KeyError:
Tim Peters21429932004-07-21 03:36:52 +0000576 if 'dummy_threading' not in _sys.modules:
577 raise
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000578 finally:
579 _active_limbo_lock.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000580
581 def join(self, timeout=None):
Collin Winter50b79ce2007-06-06 00:17:35 +0000582 if not self.__initialized:
583 raise RuntimeError("Thread.__init__() not called")
584 if not self.__started:
585 raise RuntimeError("cannot join thread before it is started")
586 if self is currentThread():
587 raise RuntimeError("cannot join current thread")
588
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000589 if __debug__:
590 if not self.__stopped:
591 self._note("%s.join(): waiting until thread stops", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000592 self.__block.acquire()
593 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000594 if timeout is None:
595 while not self.__stopped:
596 self.__block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000597 if __debug__:
598 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000599 else:
600 deadline = _time() + timeout
601 while not self.__stopped:
602 delay = deadline - _time()
603 if delay <= 0:
604 if __debug__:
605 self._note("%s.join(): timed out", self)
606 break
607 self.__block.wait(delay)
608 else:
609 if __debug__:
610 self._note("%s.join(): thread stopped", self)
Raymond Hettinger70ec29d2008-01-24 18:12:23 +0000611 finally:
612 self.__block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000613
614 def getName(self):
615 assert self.__initialized, "Thread.__init__() not called"
616 return self.__name
617
618 def setName(self, name):
619 assert self.__initialized, "Thread.__init__() not called"
620 self.__name = str(name)
621
622 def isAlive(self):
623 assert self.__initialized, "Thread.__init__() not called"
624 return self.__started and not self.__stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000625
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000626 def isDaemon(self):
627 assert self.__initialized, "Thread.__init__() not called"
628 return self.__daemonic
629
630 def setDaemon(self, daemonic):
Collin Winter50b79ce2007-06-06 00:17:35 +0000631 if not self.__initialized:
632 raise RuntimeError("Thread.__init__() not called")
633 if self.__started:
634 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000635 self.__daemonic = daemonic
636
Martin v. Löwis44f86962001-09-05 13:44:54 +0000637# The timer class was contributed by Itamar Shtull-Trauring
638
639def Timer(*args, **kwargs):
640 return _Timer(*args, **kwargs)
641
642class _Timer(Thread):
643 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000644
Martin v. Löwis44f86962001-09-05 13:44:54 +0000645 t = Timer(30.0, f, args=[], kwargs={})
646 t.start()
647 t.cancel() # stop the timer's action if it's still waiting
648 """
Tim Petersb64bec32001-09-18 02:26:39 +0000649
Martin v. Löwis44f86962001-09-05 13:44:54 +0000650 def __init__(self, interval, function, args=[], kwargs={}):
651 Thread.__init__(self)
652 self.interval = interval
653 self.function = function
654 self.args = args
655 self.kwargs = kwargs
656 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000657
Martin v. Löwis44f86962001-09-05 13:44:54 +0000658 def cancel(self):
659 """Stop the timer if it hasn't finished yet"""
660 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000661
Martin v. Löwis44f86962001-09-05 13:44:54 +0000662 def run(self):
663 self.finished.wait(self.interval)
664 if not self.finished.isSet():
665 self.function(*self.args, **self.kwargs)
666 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000667
668# Special thread class to represent the main thread
669# This is garbage collected through an exit handler
670
671class _MainThread(Thread):
672
673 def __init__(self):
674 Thread.__init__(self, name="MainThread")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000675 self._Thread__started = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000676 _active_limbo_lock.acquire()
677 _active[_get_ident()] = self
678 _active_limbo_lock.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000679
680 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000681 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000682
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000683 def _exitfunc(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000684 self._Thread__stop()
685 t = _pickSomeNonDaemonThread()
686 if t:
687 if __debug__:
688 self._note("%s: waiting for other threads", self)
689 while t:
690 t.join()
691 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000692 if __debug__:
693 self._note("%s: exiting", self)
694 self._Thread__delete()
695
696def _pickSomeNonDaemonThread():
697 for t in enumerate():
698 if not t.isDaemon() and t.isAlive():
699 return t
700 return None
701
702
703# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000704# These aren't garbage collected when they die, nor can they be waited for.
705# If they invoke anything in threading.py that calls currentThread(), they
706# leave an entry in the _active dict forever after.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000707# Their purpose is to return *something* from currentThread().
708# They are marked as daemon threads so we won't wait for them
709# when we exit (conform previous semantics).
710
711class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000712
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000713 def __init__(self):
714 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000715
716 # Thread.__block consumes an OS-level locking primitive, which
717 # can never be used by a _DummyThread. Since a _DummyThread
718 # instance is immortal, that's bad, so release this resource.
Brett Cannone6539c42005-01-08 02:43:53 +0000719 del self._Thread__block
Tim Peters711906e2005-01-08 07:30:42 +0000720
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000721 self._Thread__started = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000722 _active_limbo_lock.acquire()
723 _active[_get_ident()] = self
724 _active_limbo_lock.release()
725
726 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000727 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000728
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000729 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000730 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000731
732
733# Global API functions
734
735def currentThread():
736 try:
737 return _active[_get_ident()]
738 except KeyError:
Guido van Rossum5080b332000-12-15 20:08:39 +0000739 ##print "currentThread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000740 return _DummyThread()
741
742def activeCount():
743 _active_limbo_lock.acquire()
744 count = len(_active) + len(_limbo)
745 _active_limbo_lock.release()
746 return count
747
748def enumerate():
749 _active_limbo_lock.acquire()
750 active = _active.values() + _limbo.values()
751 _active_limbo_lock.release()
752 return active
753
Andrew MacIntyre92913322006-06-13 15:04:24 +0000754from thread import stack_size
755
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000756# Create the main thread object,
757# and make it available for the interpreter
758# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000759
Martin v. Löwis7b7c9d42007-01-04 21:06:12 +0000760_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000761
Jim Fultond15dc062004-07-14 19:11:50 +0000762# get thread-local implementation, either from the thread
763# module, or from the python fallback
764
765try:
766 from thread import _local as local
767except ImportError:
768 from _threading_local import local
769
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000770
771# Self-test code
772
773def _test():
774
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000775 class BoundedQueue(_Verbose):
776
777 def __init__(self, limit):
778 _Verbose.__init__(self)
779 self.mon = RLock()
780 self.rc = Condition(self.mon)
781 self.wc = Condition(self.mon)
782 self.limit = limit
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000783 self.queue = deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000784
785 def put(self, item):
786 self.mon.acquire()
787 while len(self.queue) >= self.limit:
788 self._note("put(%s): queue full", item)
789 self.wc.wait()
790 self.queue.append(item)
791 self._note("put(%s): appended, length now %d",
792 item, len(self.queue))
793 self.rc.notify()
794 self.mon.release()
795
796 def get(self):
797 self.mon.acquire()
798 while not self.queue:
799 self._note("get(): queue empty")
800 self.rc.wait()
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000801 item = self.queue.popleft()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000802 self._note("get(): got %s, %d left", item, len(self.queue))
803 self.wc.notify()
804 self.mon.release()
805 return item
806
807 class ProducerThread(Thread):
808
809 def __init__(self, queue, quota):
810 Thread.__init__(self, name="Producer")
811 self.queue = queue
812 self.quota = quota
813
814 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000815 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000816 counter = 0
817 while counter < self.quota:
818 counter = counter + 1
819 self.queue.put("%s.%d" % (self.getName(), counter))
820 _sleep(random() * 0.00001)
821
822
823 class ConsumerThread(Thread):
824
825 def __init__(self, queue, count):
826 Thread.__init__(self, name="Consumer")
827 self.queue = queue
828 self.count = count
829
830 def run(self):
831 while self.count > 0:
832 item = self.queue.get()
833 print item
834 self.count = self.count - 1
835
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000836 NP = 3
837 QL = 4
838 NI = 5
839
840 Q = BoundedQueue(QL)
841 P = []
842 for i in range(NP):
843 t = ProducerThread(Q, NI)
844 t.setName("Producer-%d" % (i+1))
845 P.append(t)
846 C = ConsumerThread(Q, NI*NP)
847 for t in P:
848 t.start()
849 _sleep(0.000001)
850 C.start()
851 for t in P:
852 t.join()
853 C.join()
854
855if __name__ == '__main__':
856 _test()