blob: 2ca224e26bdff36e1fee801239f08984e9396800 [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()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000235 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000236 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000237 else:
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000238 if timeout > 0:
239 gotit = waiter.acquire(True, timeout)
240 else:
241 gotit = waiter.acquire(False)
Tim Petersc951bf92001-04-02 20:15:57 +0000242 if not gotit:
243 if __debug__:
244 self._note("%s.wait(%s): timed out", self, timeout)
245 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000246 self._waiters.remove(waiter)
Tim Petersc951bf92001-04-02 20:15:57 +0000247 except ValueError:
248 pass
249 else:
250 if __debug__:
251 self._note("%s.wait(%s): got it", self, timeout)
252 finally:
253 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000254
255 def notify(self, n=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000256 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000257 raise RuntimeError("cannot notify on un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000258 __waiters = self._waiters
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000259 waiters = __waiters[:n]
260 if not waiters:
261 if __debug__:
262 self._note("%s.notify(): no waiters", self)
263 return
264 self._note("%s.notify(): notifying %d waiter%s", self, n,
265 n!=1 and "s" or "")
266 for waiter in waiters:
267 waiter.release()
268 try:
269 __waiters.remove(waiter)
270 except ValueError:
271 pass
272
Benjamin Peterson672b8032008-06-11 19:14:14 +0000273 def notify_all(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000274 self.notify(len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000275
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000276 notifyAll = notify_all
277
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000278
279def Semaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000280 return _Semaphore(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000281
282class _Semaphore(_Verbose):
283
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000284 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000285
286 def __init__(self, value=1, verbose=None):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000287 if value < 0:
288 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000289 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000290 self._cond = Condition(Lock())
291 self._value = value
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000292
Antoine Pitrou0454af92010-04-17 23:51:58 +0000293 def acquire(self, blocking=True, timeout=None):
294 if not blocking and timeout is not None:
295 raise ValueError("can't specify timeout for non-blocking acquire")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000296 rc = False
Antoine Pitrou0454af92010-04-17 23:51:58 +0000297 endtime = None
Guido van Rossumd0648992007-08-20 19:25:41 +0000298 self._cond.acquire()
299 while self._value == 0:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000300 if not blocking:
301 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000302 if __debug__:
303 self._note("%s.acquire(%s): blocked waiting, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000304 self, blocking, self._value)
Antoine Pitrou0454af92010-04-17 23:51:58 +0000305 if timeout is not None:
306 if endtime is None:
307 endtime = _time() + timeout
308 else:
309 timeout = endtime - _time()
310 if timeout <= 0:
311 break
312 self._cond.wait(timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000313 else:
Guido van Rossumd0648992007-08-20 19:25:41 +0000314 self._value = self._value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000315 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000316 self._note("%s.acquire: success, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000317 self, self._value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000318 rc = True
Guido van Rossumd0648992007-08-20 19:25:41 +0000319 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000320 return rc
321
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000322 __enter__ = acquire
323
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000324 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000325 self._cond.acquire()
326 self._value = self._value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000327 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000328 self._note("%s.release: success, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000329 self, self._value)
330 self._cond.notify()
331 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000332
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000333 def __exit__(self, t, v, tb):
334 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000335
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000336
Skip Montanaroe428bb72001-08-20 20:27:58 +0000337def BoundedSemaphore(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000338 return _BoundedSemaphore(*args, **kwargs)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000339
340class _BoundedSemaphore(_Semaphore):
341 """Semaphore that checks that # releases is <= # acquires"""
342 def __init__(self, value=1, verbose=None):
343 _Semaphore.__init__(self, value, verbose)
344 self._initial_value = value
345
346 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000347 if self._value >= self._initial_value:
Collin Winterce36ad82007-08-30 01:19:48 +0000348 raise ValueError("Semaphore released too many times")
Skip Montanaroe428bb72001-08-20 20:27:58 +0000349 return _Semaphore.release(self)
350
351
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000352def Event(*args, **kwargs):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000353 return _Event(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000354
355class _Event(_Verbose):
356
357 # After Tim Peters' event class (without is_posted())
358
359 def __init__(self, verbose=None):
360 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000361 self._cond = Condition(Lock())
362 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000363
Benjamin Peterson672b8032008-06-11 19:14:14 +0000364 def is_set(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000365 return self._flag
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000366
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000367 isSet = is_set
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000368
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000369 def set(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000370 self._cond.acquire()
371 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000372 self._flag = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000373 self._cond.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000374 finally:
375 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000376
377 def clear(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000378 self._cond.acquire()
379 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000380 self._flag = False
Christian Heimes969fe572008-01-25 11:23:10 +0000381 finally:
382 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000383
384 def wait(self, timeout=None):
Christian Heimes969fe572008-01-25 11:23:10 +0000385 self._cond.acquire()
386 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000387 if not self._flag:
388 self._cond.wait(timeout)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000389 return self._flag
Christian Heimes969fe572008-01-25 11:23:10 +0000390 finally:
391 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000392
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000393# Helper to generate new thread names
394_counter = 0
395def _newname(template="Thread-%d"):
396 global _counter
397 _counter = _counter + 1
398 return template % _counter
399
400# Active thread administration
401_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000402_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000403_limbo = {}
404
405
406# Main class for threads
407
408class Thread(_Verbose):
409
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000410 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000411 # Need to store a reference to sys.exc_info for printing
412 # out exceptions when a thread tries to use a global var. during interp.
413 # shutdown and thus raises an exception about trying to perform some
414 # operation on/with a NoneType
415 __exc_info = _sys.exc_info
Christian Heimesbbe741d2008-03-28 10:53:29 +0000416 # Keep sys.exc_clear too to clear the exception just before
417 # allowing .join() to return.
418 #XXX __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000419
420 def __init__(self, group=None, target=None, name=None,
Georg Brandla4a8b822005-07-15 09:13:21 +0000421 args=(), kwargs=None, verbose=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000422 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000423 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000424 if kwargs is None:
425 kwargs = {}
Guido van Rossumd0648992007-08-20 19:25:41 +0000426 self._target = target
427 self._name = str(name or _newname())
428 self._args = args
429 self._kwargs = kwargs
430 self._daemonic = self._set_daemon()
Georg Brandl0c77a822008-06-10 16:37:50 +0000431 self._ident = None
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000432 self._started = Event()
Guido van Rossumd0648992007-08-20 19:25:41 +0000433 self._stopped = False
434 self._block = Condition(Lock())
435 self._initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000436 # sys.stderr is not stored in the class like
437 # sys.exc_info since it can be changed between instances
Guido van Rossumd0648992007-08-20 19:25:41 +0000438 self._stderr = _sys.stderr
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000439
440 def _set_daemon(self):
441 # Overridden in _MainThread and _DummyThread
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000442 return current_thread().daemon
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000443
444 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000445 assert self._initialized, "Thread.__init__() was not called"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000446 status = "initial"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000447 if self._started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000448 status = "started"
Guido van Rossumd0648992007-08-20 19:25:41 +0000449 if self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000450 status = "stopped"
Guido van Rossumd0648992007-08-20 19:25:41 +0000451 if self._daemonic:
Georg Brandl0c77a822008-06-10 16:37:50 +0000452 status += " daemon"
453 if self._ident is not None:
454 status += " %s" % self._ident
Guido van Rossumd0648992007-08-20 19:25:41 +0000455 return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000456
457 def start(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000458 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000459 raise RuntimeError("thread.__init__() not called")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000460
Benjamin Peterson672b8032008-06-11 19:14:14 +0000461 if self._started.is_set():
Senthil Kumaranfdd4d0f2010-04-06 03:30:18 +0000462 raise RuntimeError("threads can only be started once")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000463 if __debug__:
464 self._note("%s.start(): starting thread", self)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000465 with _active_limbo_lock:
466 _limbo[self] = self
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000467 try:
468 _start_new_thread(self._bootstrap, ())
469 except Exception:
470 with _active_limbo_lock:
471 del _limbo[self]
472 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000473 self._started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000474
475 def run(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000476 try:
477 if self._target:
478 self._target(*self._args, **self._kwargs)
479 finally:
480 # Avoid a refcycle if the thread is running a function with
481 # an argument that has a member that points to the thread.
482 del self._target, self._args, self._kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000483
Guido van Rossumd0648992007-08-20 19:25:41 +0000484 def _bootstrap(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000485 # Wrapper around the real bootstrap code that ignores
486 # exceptions during interpreter cleanup. Those typically
487 # happen when a daemon thread wakes up at an unfortunate
488 # moment, finds the world around it destroyed, and raises some
489 # random exception *** while trying to report the exception in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000490 # _bootstrap_inner() below ***. Those random exceptions
Guido van Rossum61e21b52007-08-20 19:06:03 +0000491 # don't help anybody, and they confuse users, so we suppress
492 # them. We suppress them only when it appears that the world
493 # indeed has already been destroyed, so that exceptions in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000494 # _bootstrap_inner() during normal business hours are properly
Guido van Rossum61e21b52007-08-20 19:06:03 +0000495 # reported. Also, we only suppress them for daemonic threads;
496 # if a non-daemonic encounters this, something else is wrong.
497 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000498 self._bootstrap_inner()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000499 except:
Guido van Rossumd0648992007-08-20 19:25:41 +0000500 if self._daemonic and _sys is None:
Guido van Rossum61e21b52007-08-20 19:06:03 +0000501 return
502 raise
503
Benjamin Petersond23f8222009-04-05 19:13:16 +0000504 def _set_ident(self):
505 self._ident = _get_ident()
506
Guido van Rossumd0648992007-08-20 19:25:41 +0000507 def _bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000508 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000509 self._set_ident()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000510 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000511 with _active_limbo_lock:
512 _active[self._ident] = self
513 del _limbo[self]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000514 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000515 self._note("%s._bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000516
517 if _trace_hook:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000518 self._note("%s._bootstrap(): registering trace hook", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000519 _sys.settrace(_trace_hook)
520 if _profile_hook:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000521 self._note("%s._bootstrap(): registering profile hook", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000522 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000523
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000524 try:
525 self.run()
526 except SystemExit:
527 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000528 self._note("%s._bootstrap(): raised SystemExit", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000529 except:
530 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000531 self._note("%s._bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000532 # If sys.stderr is no more (most likely from interpreter
Guido van Rossumd0648992007-08-20 19:25:41 +0000533 # shutdown) use self._stderr. Otherwise still use sys (as in
Brett Cannoncc4e9352004-07-03 03:52:35 +0000534 # _sys) in case sys.stderr was redefined since the creation of
535 # self.
536 if _sys:
537 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000538 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000539 else:
540 # Do the best job possible w/o a huge amt. of code to
541 # approximate a traceback (code ideas from
542 # Lib/traceback.py)
Guido van Rossumd0648992007-08-20 19:25:41 +0000543 exc_type, exc_value, exc_tb = self._exc_info()
Brett Cannoncc4e9352004-07-03 03:52:35 +0000544 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000545 print((
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000546 "Exception in thread " + self.name +
Guido van Rossumd0648992007-08-20 19:25:41 +0000547 " (most likely raised during interpreter shutdown):"), file=self._stderr)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000548 print((
Guido van Rossumd0648992007-08-20 19:25:41 +0000549 "Traceback (most recent call last):"), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000550 while exc_tb:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000551 print((
Brett Cannoncc4e9352004-07-03 03:52:35 +0000552 ' File "%s", line %s, in %s' %
553 (exc_tb.tb_frame.f_code.co_filename,
554 exc_tb.tb_lineno,
Guido van Rossumd0648992007-08-20 19:25:41 +0000555 exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000556 exc_tb = exc_tb.tb_next
Guido van Rossumd0648992007-08-20 19:25:41 +0000557 print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000558 # Make sure that exc_tb gets deleted since it is a memory
559 # hog; deleting everything else is just for thoroughness
560 finally:
561 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000562 else:
563 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000564 self._note("%s._bootstrap(): normal return", self)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000565 finally:
566 # Prevent a race in
567 # test_threading.test_no_refcycle_through_target when
568 # the exception keeps the target alive past when we
569 # assert that it's dead.
570 #XXX self.__exc_clear()
571 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000572 finally:
Christian Heimes1af737c2008-01-23 08:24:23 +0000573 with _active_limbo_lock:
574 self._stop()
575 try:
Georg Brandl0c77a822008-06-10 16:37:50 +0000576 # We don't call self._delete() because it also
Christian Heimes1af737c2008-01-23 08:24:23 +0000577 # grabs _active_limbo_lock.
578 del _active[_get_ident()]
579 except:
580 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000581
Guido van Rossumd0648992007-08-20 19:25:41 +0000582 def _stop(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000583 self._block.acquire()
584 self._stopped = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000585 self._block.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000586 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000587
Guido van Rossumd0648992007-08-20 19:25:41 +0000588 def _delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000589 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000590
Georg Brandl2067bfd2008-05-25 13:05:15 +0000591 # Notes about running with _dummy_thread:
Tim Peters21429932004-07-21 03:36:52 +0000592 #
Georg Brandl2067bfd2008-05-25 13:05:15 +0000593 # Must take care to not raise an exception if _dummy_thread is being
Tim Peters21429932004-07-21 03:36:52 +0000594 # used (and thus this module is being used as an instance of
Georg Brandl2067bfd2008-05-25 13:05:15 +0000595 # dummy_threading). _dummy_thread.get_ident() always returns -1 since
596 # there is only one thread if _dummy_thread is being used. Thus
Tim Peters21429932004-07-21 03:36:52 +0000597 # len(_active) is always <= 1 here, and any Thread instance created
598 # overwrites the (if any) thread currently registered in _active.
599 #
600 # An instance of _MainThread is always created by 'threading'. This
601 # gets overwritten the instant an instance of Thread is created; both
Georg Brandl2067bfd2008-05-25 13:05:15 +0000602 # threads return -1 from _dummy_thread.get_ident() and thus have the
Tim Peters21429932004-07-21 03:36:52 +0000603 # same key in the dict. So when the _MainThread instance created by
604 # 'threading' tries to clean itself up when atexit calls this method
605 # it gets a KeyError if another Thread instance was created.
606 #
607 # This all means that KeyError from trying to delete something from
608 # _active if dummy_threading is being used is a red herring. But
609 # since it isn't if dummy_threading is *not* being used then don't
610 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000611
Christian Heimes969fe572008-01-25 11:23:10 +0000612 try:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000613 with _active_limbo_lock:
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000614 del _active[_get_ident()]
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000615 # There must not be any python code between the previous line
616 # and after the lock is released. Otherwise a tracing function
617 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson672b8032008-06-11 19:14:14 +0000618 # current_thread()), and would block.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000619 except KeyError:
620 if 'dummy_threading' not in _sys.modules:
621 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000622
623 def join(self, timeout=None):
Guido van Rossumd0648992007-08-20 19:25:41 +0000624 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000625 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000626 if not self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000627 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000628 if self is current_thread():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000629 raise RuntimeError("cannot join current thread")
630
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000631 if __debug__:
Guido van Rossumd0648992007-08-20 19:25:41 +0000632 if not self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000633 self._note("%s.join(): waiting until thread stops", self)
Christian Heimes969fe572008-01-25 11:23:10 +0000634
635 self._block.acquire()
636 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000637 if timeout is None:
Guido van Rossumd0648992007-08-20 19:25:41 +0000638 while not self._stopped:
639 self._block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000640 if __debug__:
641 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000642 else:
643 deadline = _time() + timeout
Guido van Rossumd0648992007-08-20 19:25:41 +0000644 while not self._stopped:
Brett Cannonad07ff22005-11-23 02:15:50 +0000645 delay = deadline - _time()
646 if delay <= 0:
647 if __debug__:
648 self._note("%s.join(): timed out", self)
649 break
Guido van Rossumd0648992007-08-20 19:25:41 +0000650 self._block.wait(delay)
Brett Cannonad07ff22005-11-23 02:15:50 +0000651 else:
652 if __debug__:
653 self._note("%s.join(): thread stopped", self)
Christian Heimes969fe572008-01-25 11:23:10 +0000654 finally:
655 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000656
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000657 @property
658 def name(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000659 assert self._initialized, "Thread.__init__() not called"
660 return self._name
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000661
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000662 @name.setter
663 def name(self, name):
Guido van Rossumd0648992007-08-20 19:25:41 +0000664 assert self._initialized, "Thread.__init__() not called"
665 self._name = str(name)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000666
Benjamin Peterson773c17b2008-08-18 16:45:31 +0000667 @property
668 def ident(self):
Georg Brandl0c77a822008-06-10 16:37:50 +0000669 assert self._initialized, "Thread.__init__() not called"
670 return self._ident
671
Benjamin Peterson672b8032008-06-11 19:14:14 +0000672 def is_alive(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000673 assert self._initialized, "Thread.__init__() not called"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000674 return self._started.is_set() and not self._stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000675
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000676 isAlive = is_alive
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000677
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000678 @property
679 def daemon(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000680 assert self._initialized, "Thread.__init__() not called"
681 return self._daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000682
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000683 @daemon.setter
684 def daemon(self, daemonic):
Guido van Rossumd0648992007-08-20 19:25:41 +0000685 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000686 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000687 if self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000688 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossumd0648992007-08-20 19:25:41 +0000689 self._daemonic = daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000690
Benjamin Peterson6640d722008-08-18 18:16:46 +0000691 def isDaemon(self):
692 return self.daemon
693
694 def setDaemon(self, daemonic):
695 self.daemon = daemonic
696
697 def getName(self):
698 return self.name
699
700 def setName(self, name):
701 self.name = name
702
Martin v. Löwis44f86962001-09-05 13:44:54 +0000703# The timer class was contributed by Itamar Shtull-Trauring
704
705def Timer(*args, **kwargs):
706 return _Timer(*args, **kwargs)
707
708class _Timer(Thread):
709 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000710
Martin v. Löwis44f86962001-09-05 13:44:54 +0000711 t = Timer(30.0, f, args=[], kwargs={})
712 t.start()
713 t.cancel() # stop the timer's action if it's still waiting
714 """
Tim Petersb64bec32001-09-18 02:26:39 +0000715
Martin v. Löwis44f86962001-09-05 13:44:54 +0000716 def __init__(self, interval, function, args=[], kwargs={}):
717 Thread.__init__(self)
718 self.interval = interval
719 self.function = function
720 self.args = args
721 self.kwargs = kwargs
722 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000723
Martin v. Löwis44f86962001-09-05 13:44:54 +0000724 def cancel(self):
725 """Stop the timer if it hasn't finished yet"""
726 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000727
Martin v. Löwis44f86962001-09-05 13:44:54 +0000728 def run(self):
729 self.finished.wait(self.interval)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000730 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000731 self.function(*self.args, **self.kwargs)
732 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000733
734# Special thread class to represent the main thread
735# This is garbage collected through an exit handler
736
737class _MainThread(Thread):
738
739 def __init__(self):
740 Thread.__init__(self, name="MainThread")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000741 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000742 self._set_ident()
743 with _active_limbo_lock:
744 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000745
746 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000747 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000748
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000749 def _exitfunc(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000750 self._stop()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000751 t = _pickSomeNonDaemonThread()
752 if t:
753 if __debug__:
754 self._note("%s: waiting for other threads", self)
755 while t:
756 t.join()
757 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000758 if __debug__:
759 self._note("%s: exiting", self)
Guido van Rossumd0648992007-08-20 19:25:41 +0000760 self._delete()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000761
762def _pickSomeNonDaemonThread():
763 for t in enumerate():
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000764 if not t.daemon and t.is_alive():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000765 return t
766 return None
767
768
769# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000770# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000771# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000772# leave an entry in the _active dict forever after.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000773# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000774# They are marked as daemon threads so we won't wait for them
775# when we exit (conform previous semantics).
776
777class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000778
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000779 def __init__(self):
780 Thread.__init__(self, name=_newname("Dummy-%d"))
Tim Peters711906e2005-01-08 07:30:42 +0000781
782 # Thread.__block consumes an OS-level locking primitive, which
783 # can never be used by a _DummyThread. Since a _DummyThread
784 # instance is immortal, that's bad, so release this resource.
Guido van Rossumd0648992007-08-20 19:25:41 +0000785 del self._block
Tim Peters711906e2005-01-08 07:30:42 +0000786
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000787
788 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000789 self._set_ident()
790 with _active_limbo_lock:
791 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000792
793 def _set_daemon(self):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000794 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000795
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000796 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000797 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000798
799
800# Global API functions
801
Benjamin Peterson672b8032008-06-11 19:14:14 +0000802def current_thread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000803 try:
804 return _active[_get_ident()]
805 except KeyError:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000806 ##print "current_thread(): no current thread for", _get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000807 return _DummyThread()
808
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000809currentThread = current_thread
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000810
Benjamin Peterson672b8032008-06-11 19:14:14 +0000811def active_count():
Benjamin Petersond23f8222009-04-05 19:13:16 +0000812 with _active_limbo_lock:
813 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000814
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000815activeCount = active_count
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000816
Antoine Pitroubdec11f2009-11-05 13:49:14 +0000817def _enumerate():
818 # Same as enumerate(), but without the lock. Internal use only.
819 return list(_active.values()) + list(_limbo.values())
820
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000821def enumerate():
Benjamin Petersond23f8222009-04-05 19:13:16 +0000822 with _active_limbo_lock:
823 return list(_active.values()) + list(_limbo.values())
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000824
Georg Brandl2067bfd2008-05-25 13:05:15 +0000825from _thread import stack_size
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000826
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000827# Create the main thread object,
828# and make it available for the interpreter
829# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000830
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000831_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000832
Jim Fultond15dc062004-07-14 19:11:50 +0000833# get thread-local implementation, either from the thread
834# module, or from the python fallback
835
836try:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000837 from _thread import _local as local
Jim Fultond15dc062004-07-14 19:11:50 +0000838except ImportError:
839 from _threading_local import local
840
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000841
Jesse Nollera8513972008-07-17 16:49:17 +0000842def _after_fork():
843 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
844 # is called from PyOS_AfterFork. Here we cleanup threading module state
845 # that should not exist after a fork.
846
847 # Reset _active_limbo_lock, in case we forked while the lock was held
848 # by another (non-forked) thread. http://bugs.python.org/issue874900
849 global _active_limbo_lock
850 _active_limbo_lock = _allocate_lock()
851
852 # fork() only copied the current thread; clear references to others.
853 new_active = {}
854 current = current_thread()
855 with _active_limbo_lock:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000856 for thread in _active.values():
Jesse Nollera8513972008-07-17 16:49:17 +0000857 if thread is current:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000858 # There is only one active thread. We reset the ident to
859 # its new value since it can have changed.
860 ident = _get_ident()
861 thread._ident = ident
Jesse Nollera8513972008-07-17 16:49:17 +0000862 new_active[ident] = thread
863 else:
864 # All the others are already stopped.
865 # We don't call _Thread__stop() because it tries to acquire
866 # thread._Thread__block which could also have been held while
867 # we forked.
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000868 thread._stopped = True
Jesse Nollera8513972008-07-17 16:49:17 +0000869
870 _limbo.clear()
871 _active.clear()
872 _active.update(new_active)
873 assert len(_active) == 1
874
875
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000876# Self-test code
877
878def _test():
879
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000880 class BoundedQueue(_Verbose):
881
882 def __init__(self, limit):
883 _Verbose.__init__(self)
884 self.mon = RLock()
885 self.rc = Condition(self.mon)
886 self.wc = Condition(self.mon)
887 self.limit = limit
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000888 self.queue = deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000889
890 def put(self, item):
891 self.mon.acquire()
892 while len(self.queue) >= self.limit:
893 self._note("put(%s): queue full", item)
894 self.wc.wait()
895 self.queue.append(item)
896 self._note("put(%s): appended, length now %d",
897 item, len(self.queue))
898 self.rc.notify()
899 self.mon.release()
900
901 def get(self):
902 self.mon.acquire()
903 while not self.queue:
904 self._note("get(): queue empty")
905 self.rc.wait()
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000906 item = self.queue.popleft()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000907 self._note("get(): got %s, %d left", item, len(self.queue))
908 self.wc.notify()
909 self.mon.release()
910 return item
911
912 class ProducerThread(Thread):
913
914 def __init__(self, queue, quota):
915 Thread.__init__(self, name="Producer")
916 self.queue = queue
917 self.quota = quota
918
919 def run(self):
Guido van Rossumb26a1b41998-05-20 17:05:52 +0000920 from random import random
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000921 counter = 0
922 while counter < self.quota:
923 counter = counter + 1
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000924 self.queue.put("%s.%d" % (self.name, counter))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000925 _sleep(random() * 0.00001)
926
927
928 class ConsumerThread(Thread):
929
930 def __init__(self, queue, count):
931 Thread.__init__(self, name="Consumer")
932 self.queue = queue
933 self.count = count
934
935 def run(self):
936 while self.count > 0:
937 item = self.queue.get()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000938 print(item)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000939 self.count = self.count - 1
940
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000941 NP = 3
942 QL = 4
943 NI = 5
944
945 Q = BoundedQueue(QL)
946 P = []
947 for i in range(NP):
948 t = ProducerThread(Q, NI)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000949 t.name = "Producer-%d" % (i+1)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000950 P.append(t)
951 C = ConsumerThread(Q, NI*NP)
952 for t in P:
953 t.start()
954 _sleep(0.000001)
955 C.start()
956 for t in P:
957 t.join()
958 C.join()
959
960if __name__ == '__main__':
961 _test()