blob: 238a5c4508ff7482a3ac726e8bbedda53aaa6878 [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
Georg Brandl2067bfd2008-05-25 13:05:15 +00004import _thread
Fred Drakea8725952002-12-30 23:32:50 +00005
Fred Drakea8725952002-12-30 23:32:50 +00006from time import time as _time, sleep as _sleep
Neil Schemenauerf607fc52003-11-05 23:03:00 +00007from traceback import format_exc as _format_exc
Raymond Hettinger756b3f32004-01-29 06:37:52 +00008from collections import deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +00009
Benjamin Petersonb3085c92008-09-01 23:09:31 +000010# Note regarding PEP 8 compliant names
11# This threading model was originally inspired by Java, and inherited
12# the convention of camelCase function and method names from that
13# language. Those originaly names are not in any imminent danger of
14# being deprecated (even for Py3k),so this module provides them as an
15# alias for the PEP 8 compliant names
16# Note that using the new PEP 8 compliant names facilitates substitution
17# with the multiprocessing module, which doesn't provide the old
18# Java inspired names.
19
20
Guido van Rossum7f5013a1998-04-09 22:01:42 +000021# Rename some stuff so "from threading import *" is safe
Benjamin Peterson672b8032008-06-11 19:14:14 +000022__all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
Tim Peters685e6972003-06-29 16:50:06 +000023 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000025
Georg Brandl2067bfd2008-05-25 13:05:15 +000026_start_new_thread = _thread.start_new_thread
27_allocate_lock = _thread.allocate_lock
28_get_ident = _thread.get_ident
29ThreadError = _thread.error
Antoine Pitrou434736a2009-11-10 18:46:01 +000030try:
31 _CRLock = _thread.RLock
32except AttributeError:
33 _CRLock = None
Antoine Pitrou7c3e5772010-04-14 15:44:10 +000034TIMEOUT_MAX = _thread.TIMEOUT_MAX
Georg Brandl2067bfd2008-05-25 13:05:15 +000035del _thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +000036
Guido van Rossum7f5013a1998-04-09 22:01:42 +000037
Tim Peters59aba122003-07-01 20:01:55 +000038# Debug support (adapted from ihooks.py).
39# All the major classes here derive from _Verbose. We force that to
40# be a new-style class so that all the major classes here are new-style.
41# This helps debugging (type(instance) is more revealing for instances
42# of new-style classes).
Guido van Rossum7f5013a1998-04-09 22:01:42 +000043
Tim Peters0939fac2003-07-01 19:28:44 +000044_VERBOSE = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +000045
46if __debug__:
47
Tim Peters59aba122003-07-01 20:01:55 +000048 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000049
50 def __init__(self, verbose=None):
51 if verbose is None:
52 verbose = _VERBOSE
Guido van Rossumd0648992007-08-20 19:25:41 +000053 self._verbose = verbose
Guido van Rossum7f5013a1998-04-09 22:01:42 +000054
55 def _note(self, format, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +000056 if self._verbose:
Guido van Rossum7f5013a1998-04-09 22:01:42 +000057 format = format % args
58 format = "%s: %s\n" % (
Benjamin Petersonfdbea962008-08-18 17:33:47 +000059 current_thread().name, format)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000060 _sys.stderr.write(format)
61
62else:
63 # Disable this when using "python -O"
Tim Peters59aba122003-07-01 20:01:55 +000064 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000065 def __init__(self, verbose=None):
66 pass
67 def _note(self, *args):
68 pass
69
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000070# Support for profile and trace hooks
71
72_profile_hook = None
73_trace_hook = None
74
75def setprofile(func):
76 global _profile_hook
77 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000078
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000079def settrace(func):
80 global _trace_hook
81 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000082
83# Synchronization classes
84
85Lock = _allocate_lock
86
Antoine Pitrou434736a2009-11-10 18:46:01 +000087def RLock(verbose=None, *args, **kwargs):
88 if verbose is None:
89 verbose = _VERBOSE
90 if (__debug__ and verbose) or _CRLock is None:
91 return _PyRLock(verbose, *args, **kwargs)
92 return _CRLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000093
94class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +000095
Guido van Rossum7f5013a1998-04-09 22:01:42 +000096 def __init__(self, verbose=None):
97 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +000098 self._block = _allocate_lock()
99 self._owner = None
100 self._count = 0
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000101
102 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000103 owner = self._owner
Antoine Pitroub0872682009-11-09 16:08:16 +0000104 try:
105 owner = _active[owner].name
106 except KeyError:
107 pass
108 return "<%s owner=%r count=%d>" % (
109 self.__class__.__name__, owner, self._count)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000110
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000111 def acquire(self, blocking=True, timeout=-1):
Antoine Pitroub0872682009-11-09 16:08:16 +0000112 me = _get_ident()
113 if self._owner == me:
Guido van Rossumd0648992007-08-20 19:25:41 +0000114 self._count = self._count + 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000115 if __debug__:
116 self._note("%s.acquire(%s): recursive success", self, blocking)
117 return 1
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000118 rc = self._block.acquire(blocking, timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000119 if rc:
Guido van Rossumd0648992007-08-20 19:25:41 +0000120 self._owner = me
121 self._count = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000122 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000123 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000124 else:
125 if __debug__:
126 self._note("%s.acquire(%s): failure", self, blocking)
127 return rc
128
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000129 __enter__ = acquire
130
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000131 def release(self):
Antoine Pitroub0872682009-11-09 16:08:16 +0000132 if self._owner != _get_ident():
Georg Brandl495f7b52009-10-27 15:28:25 +0000133 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000134 self._count = count = self._count - 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000135 if not count:
Guido van Rossumd0648992007-08-20 19:25:41 +0000136 self._owner = None
137 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000138 if __debug__:
139 self._note("%s.release(): final release", self)
140 else:
141 if __debug__:
142 self._note("%s.release(): non-final release", self)
143
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000144 def __exit__(self, t, v, tb):
145 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000146
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000147 # Internal methods used by condition variables
148
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000149 def _acquire_restore(self, state):
Guido van Rossumd0648992007-08-20 19:25:41 +0000150 self._block.acquire()
151 self._count, self._owner = state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000152 if __debug__:
153 self._note("%s._acquire_restore()", self)
154
155 def _release_save(self):
156 if __debug__:
157 self._note("%s._release_save()", self)
Guido van Rossumd0648992007-08-20 19:25:41 +0000158 count = self._count
159 self._count = 0
160 owner = self._owner
161 self._owner = None
162 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000163 return (count, owner)
164
165 def _is_owned(self):
Antoine Pitroub0872682009-11-09 16:08:16 +0000166 return self._owner == _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000167
Antoine Pitrou434736a2009-11-10 18:46:01 +0000168_PyRLock = _RLock
169
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000170
171def Condition(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000172 return _Condition(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000173
174class _Condition(_Verbose):
175
176 def __init__(self, lock=None, verbose=None):
177 _Verbose.__init__(self, verbose)
178 if lock is None:
179 lock = RLock()
Guido van Rossumd0648992007-08-20 19:25:41 +0000180 self._lock = lock
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000181 # Export the lock's acquire() and release() methods
182 self.acquire = lock.acquire
183 self.release = lock.release
184 # If the lock defines _release_save() and/or _acquire_restore(),
185 # these override the default implementations (which just call
186 # release() and acquire() on the lock). Ditto for _is_owned().
187 try:
188 self._release_save = lock._release_save
189 except AttributeError:
190 pass
191 try:
192 self._acquire_restore = lock._acquire_restore
193 except AttributeError:
194 pass
195 try:
196 self._is_owned = lock._is_owned
197 except AttributeError:
198 pass
Guido van Rossumd0648992007-08-20 19:25:41 +0000199 self._waiters = []
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000200
Thomas Wouters477c8d52006-05-27 19:21:47 +0000201 def __enter__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000202 return self._lock.__enter__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000203
Thomas Wouters477c8d52006-05-27 19:21:47 +0000204 def __exit__(self, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +0000205 return self._lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000206
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000207 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000208 return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000209
210 def _release_save(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000211 self._lock.release() # No state to save
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000212
213 def _acquire_restore(self, x):
Guido van Rossumd0648992007-08-20 19:25:41 +0000214 self._lock.acquire() # Ignore saved state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000215
216 def _is_owned(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000217 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000218 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossumd0648992007-08-20 19:25:41 +0000219 if self._lock.acquire(0):
220 self._lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000221 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000222 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000223 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000224
225 def wait(self, timeout=None):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000226 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000227 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000228 waiter = _allocate_lock()
229 waiter.acquire()
Guido van Rossumd0648992007-08-20 19:25:41 +0000230 self._waiters.append(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000231 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000232 try: # restore state no matter what (e.g., KeyboardInterrupt)
233 if timeout is None:
234 waiter.acquire()
Georg Brandlb9a43912010-10-28 09:03:20 +0000235 gotit = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000236 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000237 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000238 else:
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000239 if timeout > 0:
240 gotit = waiter.acquire(True, timeout)
241 else:
242 gotit = waiter.acquire(False)
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:
Guido van Rossumd0648992007-08-20 19:25:41 +0000247 self._waiters.remove(waiter)
Tim Petersc951bf92001-04-02 20:15:57 +0000248 except ValueError:
249 pass
250 else:
251 if __debug__:
252 self._note("%s.wait(%s): got it", self, timeout)
Georg Brandlb9a43912010-10-28 09:03:20 +0000253 return gotit
Tim Petersc951bf92001-04-02 20:15:57 +0000254 finally:
255 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000256
257 def notify(self, n=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000258 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000259 raise RuntimeError("cannot notify on un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000260 __waiters = self._waiters
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000261 waiters = __waiters[:n]
262 if not waiters:
263 if __debug__:
264 self._note("%s.notify(): no waiters", self)
265 return
266 self._note("%s.notify(): notifying %d waiter%s", self, n,
267 n!=1 and "s" or "")
268 for waiter in waiters:
269 waiter.release()
270 try:
271 __waiters.remove(waiter)
272 except ValueError:
273 pass
274
Benjamin Peterson672b8032008-06-11 19:14:14 +0000275 def notify_all(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000276 self.notify(len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000277
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000278 notifyAll = notify_all
279
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000280
281def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000282 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000283
284class _Semaphore(_Verbose):
285
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000286 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000287
288 def __init__(self, value=1, verbose=None):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000289 if value < 0:
290 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000291 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000292 self._cond = Condition(Lock())
293 self._value = value
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000294
Antoine Pitrou0454af92010-04-17 23:51:58 +0000295 def acquire(self, blocking=True, timeout=None):
296 if not blocking and timeout is not None:
297 raise ValueError("can't specify timeout for non-blocking acquire")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000298 rc = False
Antoine Pitrou0454af92010-04-17 23:51:58 +0000299 endtime = None
Guido van Rossumd0648992007-08-20 19:25:41 +0000300 self._cond.acquire()
301 while self._value == 0:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000302 if not blocking:
303 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000304 if __debug__:
305 self._note("%s.acquire(%s): blocked waiting, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000306 self, blocking, self._value)
Antoine Pitrou0454af92010-04-17 23:51:58 +0000307 if timeout is not None:
308 if endtime is None:
309 endtime = _time() + timeout
310 else:
311 timeout = endtime - _time()
312 if timeout <= 0:
313 break
314 self._cond.wait(timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000315 else:
Guido van Rossumd0648992007-08-20 19:25:41 +0000316 self._value = self._value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000317 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000318 self._note("%s.acquire: success, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000319 self, self._value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000320 rc = True
Guido van Rossumd0648992007-08-20 19:25:41 +0000321 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000322 return rc
323
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000324 __enter__ = acquire
325
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000326 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000327 self._cond.acquire()
328 self._value = self._value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000329 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000330 self._note("%s.release: success, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000331 self, self._value)
332 self._cond.notify()
333 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000334
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000335 def __exit__(self, t, v, tb):
336 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000337
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000338
Skip Montanaroe428bb72001-08-20 20:27:58 +0000339def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000340 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000341
342class _BoundedSemaphore(_Semaphore):
343 """Semaphore that checks that # releases is <= # acquires"""
344 def __init__(self, value=1, verbose=None):
345 _Semaphore.__init__(self, value, verbose)
346 self._initial_value = value
347
348 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000349 if self._value >= self._initial_value:
Collin Winterce36ad82007-08-30 01:19:48 +0000350 raise ValueError("Semaphore released too many times")
Skip Montanaroe428bb72001-08-20 20:27:58 +0000351 return _Semaphore.release(self)
352
353
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000354def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000355 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000356
357class _Event(_Verbose):
358
359 # After Tim Peters' event class (without is_posted())
360
361 def __init__(self, verbose=None):
362 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000363 self._cond = Condition(Lock())
364 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000365
Benjamin Peterson672b8032008-06-11 19:14:14 +0000366 def is_set(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000367 return self._flag
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000368
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000369 isSet = is_set
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000370
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000371 def set(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000372 self._cond.acquire()
373 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000374 self._flag = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000375 self._cond.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000376 finally:
377 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000378
379 def clear(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000380 self._cond.acquire()
381 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000382 self._flag = False
Christian Heimes969fe572008-01-25 11:23:10 +0000383 finally:
384 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000385
386 def wait(self, timeout=None):
Christian Heimes969fe572008-01-25 11:23:10 +0000387 self._cond.acquire()
388 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000389 if not self._flag:
390 self._cond.wait(timeout)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000391 return self._flag
Christian Heimes969fe572008-01-25 11:23:10 +0000392 finally:
393 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000394
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000395# Helper to generate new thread names
396_counter = 0
397def _newname(template="Thread-%d"):
398 global _counter
399 _counter = _counter + 1
400 return template % _counter
401
402# Active thread administration
403_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000404_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000405_limbo = {}
406
407
408# Main class for threads
409
410class Thread(_Verbose):
411
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000412 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000413 # Need to store a reference to sys.exc_info for printing
414 # out exceptions when a thread tries to use a global var. during interp.
415 # shutdown and thus raises an exception about trying to perform some
416 # operation on/with a NoneType
417 __exc_info = _sys.exc_info
Christian Heimesbbe741d2008-03-28 10:53:29 +0000418 # Keep sys.exc_clear too to clear the exception just before
419 # allowing .join() to return.
420 #XXX __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000421
422 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000423 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000424 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000425 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000426 if kwargs is None:
427 kwargs = {}
Guido van Rossumd0648992007-08-20 19:25:41 +0000428 self._target = target
429 self._name = str(name or _newname())
430 self._args = args
431 self._kwargs = kwargs
432 self._daemonic = self._set_daemon()
Georg Brandl0c77a822008-06-10 16:37:50 +0000433 self._ident = None
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000434 self._started = Event()
Guido van Rossumd0648992007-08-20 19:25:41 +0000435 self._stopped = False
436 self._block = Condition(Lock())
437 self._initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000438 # sys.stderr is not stored in the class like
439 # sys.exc_info since it can be changed between instances
Guido van Rossumd0648992007-08-20 19:25:41 +0000440 self._stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000441
442 def _set_daemon(self):
443 # Overridden in _MainThread and _DummyThread
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000444 return current_thread().daemon
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000445
446 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000447 assert self._initialized, "Thread.__init__() was not called"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000448 status = "initial"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000449 if self._started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000450 status = "started"
Guido van Rossumd0648992007-08-20 19:25:41 +0000451 if self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000452 status = "stopped"
Guido van Rossumd0648992007-08-20 19:25:41 +0000453 if self._daemonic:
Georg Brandl0c77a822008-06-10 16:37:50 +0000454 status += " daemon"
455 if self._ident is not None:
456 status += " %s" % self._ident
Guido van Rossumd0648992007-08-20 19:25:41 +0000457 return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000458
459 def start(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000460 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000461 raise RuntimeError("thread.__init__() not called")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000462
Benjamin Peterson672b8032008-06-11 19:14:14 +0000463 if self._started.is_set():
Senthil Kumaranfdd4d0f2010-04-06 03:30:18 +0000464 raise RuntimeError("threads can only be started once")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000465 if __debug__:
466 self._note("%s.start(): starting thread", self)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000467 with _active_limbo_lock:
468 _limbo[self] = self
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000469 try:
470 _start_new_thread(self._bootstrap, ())
471 except Exception:
472 with _active_limbo_lock:
473 del _limbo[self]
474 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000475 self._started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000476
477 def run(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000478 try:
479 if self._target:
480 self._target(*self._args, **self._kwargs)
481 finally:
482 # Avoid a refcycle if the thread is running a function with
483 # an argument that has a member that points to the thread.
484 del self._target, self._args, self._kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000485
Guido van Rossumd0648992007-08-20 19:25:41 +0000486 def _bootstrap(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000487 # Wrapper around the real bootstrap code that ignores
488 # exceptions during interpreter cleanup. Those typically
489 # happen when a daemon thread wakes up at an unfortunate
490 # moment, finds the world around it destroyed, and raises some
491 # random exception *** while trying to report the exception in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000492 # _bootstrap_inner() below ***. Those random exceptions
Guido van Rossum61e21b52007-08-20 19:06:03 +0000493 # don't help anybody, and they confuse users, so we suppress
494 # them. We suppress them only when it appears that the world
495 # indeed has already been destroyed, so that exceptions in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000496 # _bootstrap_inner() during normal business hours are properly
Guido van Rossum61e21b52007-08-20 19:06:03 +0000497 # reported. Also, we only suppress them for daemonic threads;
498 # if a non-daemonic encounters this, something else is wrong.
499 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000500 self._bootstrap_inner()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000501 except:
Guido van Rossumd0648992007-08-20 19:25:41 +0000502 if self._daemonic and _sys is None:
Guido van Rossum61e21b52007-08-20 19:06:03 +0000503 return
504 raise
505
Benjamin Petersond23f8222009-04-05 19:13:16 +0000506 def _set_ident(self):
507 self._ident = _get_ident()
508
Guido van Rossumd0648992007-08-20 19:25:41 +0000509 def _bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000510 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000511 self._set_ident()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000512 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000513 with _active_limbo_lock:
514 _active[self._ident] = self
515 del _limbo[self]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000516 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000517 self._note("%s._bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000518
519 if _trace_hook:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000520 self._note("%s._bootstrap(): registering trace hook", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000521 _sys.settrace(_trace_hook)
522 if _profile_hook:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000523 self._note("%s._bootstrap(): registering profile hook", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000524 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000525
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000526 try:
527 self.run()
528 except SystemExit:
529 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000530 self._note("%s._bootstrap(): raised SystemExit", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000531 except:
532 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000533 self._note("%s._bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000534 # If sys.stderr is no more (most likely from interpreter
Guido van Rossumd0648992007-08-20 19:25:41 +0000535 # shutdown) use self._stderr. Otherwise still use sys (as in
Brett Cannoncc4e9352004-07-03 03:52:35 +0000536 # _sys) in case sys.stderr was redefined since the creation of
537 # self.
538 if _sys:
539 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000540 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000541 else:
542 # Do the best job possible w/o a huge amt. of code to
543 # approximate a traceback (code ideas from
544 # Lib/traceback.py)
Guido van Rossumd0648992007-08-20 19:25:41 +0000545 exc_type, exc_value, exc_tb = self._exc_info()
Brett Cannoncc4e9352004-07-03 03:52:35 +0000546 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000547 print((
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000548 "Exception in thread " + self.name +
Guido van Rossumd0648992007-08-20 19:25:41 +0000549 " (most likely raised during interpreter shutdown):"), file=self._stderr)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000550 print((
Guido van Rossumd0648992007-08-20 19:25:41 +0000551 "Traceback (most recent call last):"), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000552 while exc_tb:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000553 print((
Brett Cannoncc4e9352004-07-03 03:52:35 +0000554 ' File "%s", line %s, in %s' %
555 (exc_tb.tb_frame.f_code.co_filename,
556 exc_tb.tb_lineno,
Guido van Rossumd0648992007-08-20 19:25:41 +0000557 exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000558 exc_tb = exc_tb.tb_next
Guido van Rossumd0648992007-08-20 19:25:41 +0000559 print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000560 # Make sure that exc_tb gets deleted since it is a memory
561 # hog; deleting everything else is just for thoroughness
562 finally:
563 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000564 else:
565 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000566 self._note("%s._bootstrap(): normal return", self)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000567 finally:
568 # Prevent a race in
569 # test_threading.test_no_refcycle_through_target when
570 # the exception keeps the target alive past when we
571 # assert that it's dead.
572 #XXX self.__exc_clear()
573 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000574 finally:
Christian Heimes1af737c2008-01-23 08:24:23 +0000575 with _active_limbo_lock:
576 self._stop()
577 try:
Georg Brandl0c77a822008-06-10 16:37:50 +0000578 # We don't call self._delete() because it also
Christian Heimes1af737c2008-01-23 08:24:23 +0000579 # grabs _active_limbo_lock.
580 del _active[_get_ident()]
581 except:
582 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000583
Guido van Rossumd0648992007-08-20 19:25:41 +0000584 def _stop(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000585 self._block.acquire()
586 self._stopped = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000587 self._block.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000588 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000589
Guido van Rossumd0648992007-08-20 19:25:41 +0000590 def _delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000591 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000592
Georg Brandl2067bfd2008-05-25 13:05:15 +0000593 # Notes about running with _dummy_thread:
Tim Peters21429932004-07-21 03:36:52 +0000594 #
Georg Brandl2067bfd2008-05-25 13:05:15 +0000595 # Must take care to not raise an exception if _dummy_thread is being
Tim Peters21429932004-07-21 03:36:52 +0000596 # used (and thus this module is being used as an instance of
Georg Brandl2067bfd2008-05-25 13:05:15 +0000597 # dummy_threading). _dummy_thread.get_ident() always returns -1 since
598 # there is only one thread if _dummy_thread is being used. Thus
Tim Peters21429932004-07-21 03:36:52 +0000599 # len(_active) is always <= 1 here, and any Thread instance created
600 # overwrites the (if any) thread currently registered in _active.
601 #
602 # An instance of _MainThread is always created by 'threading'. This
603 # gets overwritten the instant an instance of Thread is created; both
Georg Brandl2067bfd2008-05-25 13:05:15 +0000604 # threads return -1 from _dummy_thread.get_ident() and thus have the
Tim Peters21429932004-07-21 03:36:52 +0000605 # same key in the dict. So when the _MainThread instance created by
606 # 'threading' tries to clean itself up when atexit calls this method
607 # it gets a KeyError if another Thread instance was created.
608 #
609 # This all means that KeyError from trying to delete something from
610 # _active if dummy_threading is being used is a red herring. But
611 # since it isn't if dummy_threading is *not* being used then don't
612 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000613
Christian Heimes969fe572008-01-25 11:23:10 +0000614 try:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000615 with _active_limbo_lock:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000616 del _active[_get_ident()]
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000617 # There must not be any python code between the previous line
618 # and after the lock is released. Otherwise a tracing function
619 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson672b8032008-06-11 19:14:14 +0000620 # current_thread()), and would block.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000621 except KeyError:
622 if 'dummy_threading' not in _sys.modules:
623 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000624
625 def join(self, timeout=None):
Guido van Rossumd0648992007-08-20 19:25:41 +0000626 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000627 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000628 if not self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000629 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000630 if self is current_thread():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000631 raise RuntimeError("cannot join current thread")
632
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000633 if __debug__:
Guido van Rossumd0648992007-08-20 19:25:41 +0000634 if not self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000635 self._note("%s.join(): waiting until thread stops", self)
Christian Heimes969fe572008-01-25 11:23:10 +0000636
637 self._block.acquire()
638 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000639 if timeout is None:
Guido van Rossumd0648992007-08-20 19:25:41 +0000640 while not self._stopped:
641 self._block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000642 if __debug__:
643 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000644 else:
645 deadline = _time() + timeout
Guido van Rossumd0648992007-08-20 19:25:41 +0000646 while not self._stopped:
Brett Cannonad07ff22005-11-23 02:15:50 +0000647 delay = deadline - _time()
648 if delay <= 0:
649 if __debug__:
650 self._note("%s.join(): timed out", self)
651 break
Guido van Rossumd0648992007-08-20 19:25:41 +0000652 self._block.wait(delay)
Brett Cannonad07ff22005-11-23 02:15:50 +0000653 else:
654 if __debug__:
655 self._note("%s.join(): thread stopped", self)
Christian Heimes969fe572008-01-25 11:23:10 +0000656 finally:
657 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000658
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000659 @property
660 def name(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000661 assert self._initialized, "Thread.__init__() not called"
662 return self._name
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000663
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000664 @name.setter
665 def name(self, name):
Guido van Rossumd0648992007-08-20 19:25:41 +0000666 assert self._initialized, "Thread.__init__() not called"
667 self._name = str(name)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000668
Benjamin Peterson773c17b2008-08-18 16:45:31 +0000669 @property
670 def ident(self):
Georg Brandl0c77a822008-06-10 16:37:50 +0000671 assert self._initialized, "Thread.__init__() not called"
672 return self._ident
673
Benjamin Peterson672b8032008-06-11 19:14:14 +0000674 def is_alive(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000675 assert self._initialized, "Thread.__init__() not called"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000676 return self._started.is_set() and not self._stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000677
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000678 isAlive = is_alive
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000679
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000680 @property
681 def daemon(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000682 assert self._initialized, "Thread.__init__() not called"
683 return self._daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000684
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000685 @daemon.setter
686 def daemon(self, daemonic):
Guido van Rossumd0648992007-08-20 19:25:41 +0000687 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000688 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000689 if self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000690 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossumd0648992007-08-20 19:25:41 +0000691 self._daemonic = daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000692
Benjamin Peterson6640d722008-08-18 18:16:46 +0000693 def isDaemon(self):
694 return self.daemon
695
696 def setDaemon(self, daemonic):
697 self.daemon = daemonic
698
699 def getName(self):
700 return self.name
701
702 def setName(self, name):
703 self.name = name
704
Martin v. Löwis44f86962001-09-05 13:44:54 +0000705# The timer class was contributed by Itamar Shtull-Trauring
706
707def Timer(*args, **kwargs):
708 return _Timer(*args, **kwargs)
709
710class _Timer(Thread):
711 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000712
Martin v. Löwis44f86962001-09-05 13:44:54 +0000713 t = Timer(30.0, f, args=[], kwargs={})
714 t.start()
715 t.cancel() # stop the timer's action if it's still waiting
716 """
Tim Petersb64bec32001-09-18 02:26:39 +0000717
Martin v. Löwis44f86962001-09-05 13:44:54 +0000718 def __init__(self, interval, function, args=[], kwargs={}):
719 Thread.__init__(self)
720 self.interval = interval
721 self.function = function
722 self.args = args
723 self.kwargs = kwargs
724 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000725
Martin v. Löwis44f86962001-09-05 13:44:54 +0000726 def cancel(self):
727 """Stop the timer if it hasn't finished yet"""
728 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000729
Martin v. Löwis44f86962001-09-05 13:44:54 +0000730 def run(self):
731 self.finished.wait(self.interval)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000732 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000733 self.function(*self.args, **self.kwargs)
734 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000735
736# Special thread class to represent the main thread
737# This is garbage collected through an exit handler
738
739class _MainThread(Thread):
740
741 def __init__(self):
742 Thread.__init__(self, name="MainThread")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000743 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000744 self._set_ident()
745 with _active_limbo_lock:
746 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000747
748 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000749 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000750
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000751 def _exitfunc(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000752 self._stop()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000753 t = _pickSomeNonDaemonThread()
754 if t:
755 if __debug__:
756 self._note("%s: waiting for other threads", self)
757 while t:
758 t.join()
759 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000760 if __debug__:
761 self._note("%s: exiting", self)
Guido van Rossumd0648992007-08-20 19:25:41 +0000762 self._delete()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000763
764def _pickSomeNonDaemonThread():
765 for t in enumerate():
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000766 if not t.daemon and t.is_alive():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000767 return t
768 return None
769
770
771# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000772# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000773# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000774# leave an entry in the _active dict forever after.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000775# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000776# They are marked as daemon threads so we won't wait for them
777# when we exit (conform previous semantics).
778
779class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000780
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000781 def __init__(self):
782 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000783
784 # Thread.__block consumes an OS-level locking primitive, which
785 # can never be used by a _DummyThread. Since a _DummyThread
786 # instance is immortal, that's bad, so release this resource.
Guido van Rossumd0648992007-08-20 19:25:41 +0000787 del self._block
Tim Peters711906e2005-01-08 07:30:42 +0000788
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000789
790 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000791 self._set_ident()
792 with _active_limbo_lock:
793 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000794
795 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000796 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000797
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000798 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000799 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000800
801
802# Global API functions
803
Benjamin Peterson672b8032008-06-11 19:14:14 +0000804def current_thread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000805 try:
806 return _active[_get_ident()]
807 except KeyError:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000808 ##print "current_thread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000809 return _DummyThread()
810
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000811currentThread = current_thread
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000812
Benjamin Peterson672b8032008-06-11 19:14:14 +0000813def active_count():
Benjamin Petersond23f8222009-04-05 19:13:16 +0000814 with _active_limbo_lock:
815 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000816
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000817activeCount = active_count
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000818
Antoine Pitroubdec11f2009-11-05 13:49:14 +0000819def _enumerate():
820 # Same as enumerate(), but without the lock. Internal use only.
821 return list(_active.values()) + list(_limbo.values())
822
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000823def enumerate():
Benjamin Petersond23f8222009-04-05 19:13:16 +0000824 with _active_limbo_lock:
825 return list(_active.values()) + list(_limbo.values())
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000826
Georg Brandl2067bfd2008-05-25 13:05:15 +0000827from _thread import stack_size
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000828
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000829# Create the main thread object,
830# and make it available for the interpreter
831# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000832
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000833_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000834
Jim Fultond15dc062004-07-14 19:11:50 +0000835# get thread-local implementation, either from the thread
836# module, or from the python fallback
837
838try:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000839 from _thread import _local as local
Jim Fultond15dc062004-07-14 19:11:50 +0000840except ImportError:
841 from _threading_local import local
842
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000843
Jesse Nollera8513972008-07-17 16:49:17 +0000844def _after_fork():
845 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
846 # is called from PyOS_AfterFork. Here we cleanup threading module state
847 # that should not exist after a fork.
848
849 # Reset _active_limbo_lock, in case we forked while the lock was held
850 # by another (non-forked) thread. http://bugs.python.org/issue874900
851 global _active_limbo_lock
852 _active_limbo_lock = _allocate_lock()
853
854 # fork() only copied the current thread; clear references to others.
855 new_active = {}
856 current = current_thread()
857 with _active_limbo_lock:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000858 for thread in _active.values():
Jesse Nollera8513972008-07-17 16:49:17 +0000859 if thread is current:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000860 # There is only one active thread. We reset the ident to
861 # its new value since it can have changed.
862 ident = _get_ident()
863 thread._ident = ident
Jesse Nollera8513972008-07-17 16:49:17 +0000864 new_active[ident] = thread
865 else:
866 # All the others are already stopped.
867 # We don't call _Thread__stop() because it tries to acquire
868 # thread._Thread__block which could also have been held while
869 # we forked.
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000870 thread._stopped = True
Jesse Nollera8513972008-07-17 16:49:17 +0000871
872 _limbo.clear()
873 _active.clear()
874 _active.update(new_active)
875 assert len(_active) == 1