blob: 222e5d992afdd0c5e9968d2154596e0fb4ddddb7 [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
Antoine Pitrouc081c0c2011-07-15 22:12:24 +02009from _weakrefset import WeakSet
Guido van Rossum7f5013a1998-04-09 22:01:42 +000010
Benjamin Petersonb3085c92008-09-01 23:09:31 +000011# Note regarding PEP 8 compliant names
12# This threading model was originally inspired by Java, and inherited
13# the convention of camelCase function and method names from that
14# language. Those originaly names are not in any imminent danger of
15# being deprecated (even for Py3k),so this module provides them as an
16# alias for the PEP 8 compliant names
17# Note that using the new PEP 8 compliant names facilitates substitution
18# with the multiprocessing module, which doesn't provide the old
19# Java inspired names.
20
Benjamin Peterson672b8032008-06-11 19:14:14 +000021__all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000022 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier',
Victor Stinnerd5c355c2011-04-30 14:53:09 +020023 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000024
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000025# Rename some stuff so "from threading import *" is safe
Georg Brandl2067bfd2008-05-25 13:05:15 +000026_start_new_thread = _thread.start_new_thread
27_allocate_lock = _thread.allocate_lock
Victor Stinner2a129742011-05-30 23:02:52 +020028get_ident = _thread.get_ident
Georg Brandl2067bfd2008-05-25 13:05:15 +000029ThreadError = _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).
Guido van Rossum7f5013a1998-04-09 22:01:42 +000039
Tim Peters0939fac2003-07-01 19:28:44 +000040_VERBOSE = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +000041
42if __debug__:
43
Tim Peters59aba122003-07-01 20:01:55 +000044 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000045
46 def __init__(self, verbose=None):
47 if verbose is None:
48 verbose = _VERBOSE
Guido van Rossumd0648992007-08-20 19:25:41 +000049 self._verbose = verbose
Guido van Rossum7f5013a1998-04-09 22:01:42 +000050
51 def _note(self, format, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +000052 if self._verbose:
Guido van Rossum7f5013a1998-04-09 22:01:42 +000053 format = format % args
Antoine Pitrou401edd62010-12-17 17:42:16 +000054 # Issue #4188: calling current_thread() can incur an infinite
55 # recursion if it has to create a DummyThread on the fly.
Victor Stinner2a129742011-05-30 23:02:52 +020056 ident = get_ident()
Antoine Pitrou401edd62010-12-17 17:42:16 +000057 try:
58 name = _active[ident].name
59 except KeyError:
60 name = "<OS thread %d>" % ident
61 format = "%s: %s\n" % (name, format)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000062 _sys.stderr.write(format)
63
64else:
65 # Disable this when using "python -O"
Tim Peters59aba122003-07-01 20:01:55 +000066 class _Verbose(object):
Guido van Rossum7f5013a1998-04-09 22:01:42 +000067 def __init__(self, verbose=None):
68 pass
69 def _note(self, *args):
70 pass
71
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000072# Support for profile and trace hooks
73
74_profile_hook = None
75_trace_hook = None
76
77def setprofile(func):
78 global _profile_hook
79 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000080
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000081def settrace(func):
82 global _trace_hook
83 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000084
85# Synchronization classes
86
87Lock = _allocate_lock
88
Antoine Pitrou434736a2009-11-10 18:46:01 +000089def RLock(verbose=None, *args, **kwargs):
90 if verbose is None:
91 verbose = _VERBOSE
92 if (__debug__ and verbose) or _CRLock is None:
93 return _PyRLock(verbose, *args, **kwargs)
94 return _CRLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000095
96class _RLock(_Verbose):
Tim Petersb90f89a2001-01-15 03:26:36 +000097
Guido van Rossum7f5013a1998-04-09 22:01:42 +000098 def __init__(self, verbose=None):
99 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000100 self._block = _allocate_lock()
101 self._owner = None
102 self._count = 0
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000103
104 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000105 owner = self._owner
Antoine Pitroub0872682009-11-09 16:08:16 +0000106 try:
107 owner = _active[owner].name
108 except KeyError:
109 pass
110 return "<%s owner=%r count=%d>" % (
111 self.__class__.__name__, owner, self._count)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000112
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000113 def acquire(self, blocking=True, timeout=-1):
Victor Stinner2a129742011-05-30 23:02:52 +0200114 me = get_ident()
Antoine Pitroub0872682009-11-09 16:08:16 +0000115 if self._owner == me:
Guido van Rossumd0648992007-08-20 19:25:41 +0000116 self._count = self._count + 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000117 if __debug__:
118 self._note("%s.acquire(%s): recursive success", self, blocking)
119 return 1
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000120 rc = self._block.acquire(blocking, timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000121 if rc:
Guido van Rossumd0648992007-08-20 19:25:41 +0000122 self._owner = me
123 self._count = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000124 if __debug__:
Brett Cannon90cece72005-01-27 22:48:30 +0000125 self._note("%s.acquire(%s): initial success", self, blocking)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000126 else:
127 if __debug__:
128 self._note("%s.acquire(%s): failure", self, blocking)
129 return rc
130
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000131 __enter__ = acquire
132
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000133 def release(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200134 if self._owner != get_ident():
Georg Brandl495f7b52009-10-27 15:28:25 +0000135 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000136 self._count = count = self._count - 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000137 if not count:
Guido van Rossumd0648992007-08-20 19:25:41 +0000138 self._owner = None
139 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000140 if __debug__:
141 self._note("%s.release(): final release", self)
142 else:
143 if __debug__:
144 self._note("%s.release(): non-final release", self)
145
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000146 def __exit__(self, t, v, tb):
147 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000148
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000149 # Internal methods used by condition variables
150
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000151 def _acquire_restore(self, state):
Guido van Rossumd0648992007-08-20 19:25:41 +0000152 self._block.acquire()
153 self._count, self._owner = state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000154 if __debug__:
155 self._note("%s._acquire_restore()", self)
156
157 def _release_save(self):
158 if __debug__:
159 self._note("%s._release_save()", self)
Victor Stinnerc2824d42011-04-24 23:41:33 +0200160 if self._count == 0:
161 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000162 count = self._count
163 self._count = 0
164 owner = self._owner
165 self._owner = None
166 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000167 return (count, owner)
168
169 def _is_owned(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200170 return self._owner == get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000171
Antoine Pitrou434736a2009-11-10 18:46:01 +0000172_PyRLock = _RLock
173
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000174
Éric Araujo0cdd4452011-07-28 00:28:28 +0200175class Condition(_Verbose):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000176
177 def __init__(self, lock=None, verbose=None):
178 _Verbose.__init__(self, verbose)
179 if lock is None:
180 lock = RLock()
Guido van Rossumd0648992007-08-20 19:25:41 +0000181 self._lock = lock
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000182 # Export the lock's acquire() and release() methods
183 self.acquire = lock.acquire
184 self.release = lock.release
185 # If the lock defines _release_save() and/or _acquire_restore(),
186 # these override the default implementations (which just call
187 # release() and acquire() on the lock). Ditto for _is_owned().
188 try:
189 self._release_save = lock._release_save
190 except AttributeError:
191 pass
192 try:
193 self._acquire_restore = lock._acquire_restore
194 except AttributeError:
195 pass
196 try:
197 self._is_owned = lock._is_owned
198 except AttributeError:
199 pass
Guido van Rossumd0648992007-08-20 19:25:41 +0000200 self._waiters = []
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000201
Thomas Wouters477c8d52006-05-27 19:21:47 +0000202 def __enter__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000203 return self._lock.__enter__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000204
Thomas Wouters477c8d52006-05-27 19:21:47 +0000205 def __exit__(self, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +0000206 return self._lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000207
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000208 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000209 return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000210
211 def _release_save(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000212 self._lock.release() # No state to save
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000213
214 def _acquire_restore(self, x):
Guido van Rossumd0648992007-08-20 19:25:41 +0000215 self._lock.acquire() # Ignore saved state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000216
217 def _is_owned(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000218 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000219 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossumd0648992007-08-20 19:25:41 +0000220 if self._lock.acquire(0):
221 self._lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000222 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000223 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000224 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000225
226 def wait(self, timeout=None):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000227 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000228 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000229 waiter = _allocate_lock()
230 waiter.acquire()
Guido van Rossumd0648992007-08-20 19:25:41 +0000231 self._waiters.append(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000232 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000233 try: # restore state no matter what (e.g., KeyboardInterrupt)
234 if timeout is None:
235 waiter.acquire()
Georg Brandlb9a43912010-10-28 09:03:20 +0000236 gotit = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000237 if __debug__:
Tim Petersc951bf92001-04-02 20:15:57 +0000238 self._note("%s.wait(): got it", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000239 else:
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000240 if timeout > 0:
241 gotit = waiter.acquire(True, timeout)
242 else:
243 gotit = waiter.acquire(False)
Tim Petersc951bf92001-04-02 20:15:57 +0000244 if not gotit:
245 if __debug__:
246 self._note("%s.wait(%s): timed out", self, timeout)
247 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000248 self._waiters.remove(waiter)
Tim Petersc951bf92001-04-02 20:15:57 +0000249 except ValueError:
250 pass
251 else:
252 if __debug__:
253 self._note("%s.wait(%s): got it", self, timeout)
Georg Brandlb9a43912010-10-28 09:03:20 +0000254 return gotit
Tim Petersc951bf92001-04-02 20:15:57 +0000255 finally:
256 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000257
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000258 def wait_for(self, predicate, timeout=None):
259 endtime = None
260 waittime = timeout
261 result = predicate()
262 while not result:
263 if waittime is not None:
264 if endtime is None:
265 endtime = _time() + waittime
266 else:
267 waittime = endtime - _time()
268 if waittime <= 0:
269 if __debug__:
270 self._note("%s.wait_for(%r, %r): Timed out.",
271 self, predicate, timeout)
272 break
273 if __debug__:
274 self._note("%s.wait_for(%r, %r): Waiting with timeout=%s.",
275 self, predicate, timeout, waittime)
276 self.wait(waittime)
277 result = predicate()
278 else:
279 if __debug__:
280 self._note("%s.wait_for(%r, %r): Success.",
281 self, predicate, timeout)
282 return result
283
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000284 def notify(self, n=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000285 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000286 raise RuntimeError("cannot notify on un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000287 __waiters = self._waiters
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000288 waiters = __waiters[:n]
289 if not waiters:
290 if __debug__:
291 self._note("%s.notify(): no waiters", self)
292 return
293 self._note("%s.notify(): notifying %d waiter%s", self, n,
294 n!=1 and "s" or "")
295 for waiter in waiters:
296 waiter.release()
297 try:
298 __waiters.remove(waiter)
299 except ValueError:
300 pass
301
Benjamin Peterson672b8032008-06-11 19:14:14 +0000302 def notify_all(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000303 self.notify(len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000304
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000305 notifyAll = notify_all
306
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000307
Éric Araujo0cdd4452011-07-28 00:28:28 +0200308class Semaphore(_Verbose):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000309
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000310 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000311
312 def __init__(self, value=1, verbose=None):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000313 if value < 0:
314 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000315 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000316 self._cond = Condition(Lock())
317 self._value = value
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000318
Antoine Pitrou0454af92010-04-17 23:51:58 +0000319 def acquire(self, blocking=True, timeout=None):
320 if not blocking and timeout is not None:
321 raise ValueError("can't specify timeout for non-blocking acquire")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000322 rc = False
Antoine Pitrou0454af92010-04-17 23:51:58 +0000323 endtime = None
Guido van Rossumd0648992007-08-20 19:25:41 +0000324 self._cond.acquire()
325 while self._value == 0:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000326 if not blocking:
327 break
Skip Montanarob446fc72001-08-19 04:25:24 +0000328 if __debug__:
329 self._note("%s.acquire(%s): blocked waiting, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000330 self, blocking, self._value)
Antoine Pitrou0454af92010-04-17 23:51:58 +0000331 if timeout is not None:
332 if endtime is None:
333 endtime = _time() + timeout
334 else:
335 timeout = endtime - _time()
336 if timeout <= 0:
337 break
338 self._cond.wait(timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000339 else:
Guido van Rossumd0648992007-08-20 19:25:41 +0000340 self._value = self._value - 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000341 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000342 self._note("%s.acquire: success, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000343 self, self._value)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000344 rc = True
Guido van Rossumd0648992007-08-20 19:25:41 +0000345 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000346 return rc
347
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000348 __enter__ = acquire
349
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000350 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000351 self._cond.acquire()
352 self._value = self._value + 1
Skip Montanarob446fc72001-08-19 04:25:24 +0000353 if __debug__:
Skip Montanaroae8454a2001-08-19 05:53:47 +0000354 self._note("%s.release: success, value=%s",
Guido van Rossumd0648992007-08-20 19:25:41 +0000355 self, self._value)
356 self._cond.notify()
357 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000358
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000359 def __exit__(self, t, v, tb):
360 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000361
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000362
Éric Araujo0cdd4452011-07-28 00:28:28 +0200363class BoundedSemaphore(Semaphore):
Skip Montanaroe428bb72001-08-20 20:27:58 +0000364 """Semaphore that checks that # releases is <= # acquires"""
365 def __init__(self, value=1, verbose=None):
Éric Araujo0cdd4452011-07-28 00:28:28 +0200366 Semaphore.__init__(self, value, verbose)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000367 self._initial_value = value
368
369 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000370 if self._value >= self._initial_value:
Collin Winterce36ad82007-08-30 01:19:48 +0000371 raise ValueError("Semaphore released too many times")
Éric Araujo0cdd4452011-07-28 00:28:28 +0200372 return Semaphore.release(self)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000373
374
Éric Araujo0cdd4452011-07-28 00:28:28 +0200375class Event(_Verbose):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000376
377 # After Tim Peters' event class (without is_posted())
378
379 def __init__(self, verbose=None):
380 _Verbose.__init__(self, verbose)
Guido van Rossumd0648992007-08-20 19:25:41 +0000381 self._cond = Condition(Lock())
382 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000383
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000384 def _reset_internal_locks(self):
385 # private! called by Thread._reset_internal_locks by _after_fork()
386 self._cond.__init__()
387
Benjamin Peterson672b8032008-06-11 19:14:14 +0000388 def is_set(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000389 return self._flag
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000390
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000391 isSet = is_set
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000392
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000393 def set(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000394 self._cond.acquire()
395 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000396 self._flag = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000397 self._cond.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000398 finally:
399 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000400
401 def clear(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000402 self._cond.acquire()
403 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000404 self._flag = False
Christian Heimes969fe572008-01-25 11:23:10 +0000405 finally:
406 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000407
408 def wait(self, timeout=None):
Christian Heimes969fe572008-01-25 11:23:10 +0000409 self._cond.acquire()
410 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000411 if not self._flag:
412 self._cond.wait(timeout)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000413 return self._flag
Christian Heimes969fe572008-01-25 11:23:10 +0000414 finally:
415 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000416
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000417
418# A barrier class. Inspired in part by the pthread_barrier_* api and
419# the CyclicBarrier class from Java. See
420# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
421# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
422# CyclicBarrier.html
423# for information.
424# We maintain two main states, 'filling' and 'draining' enabling the barrier
425# to be cyclic. Threads are not allowed into it until it has fully drained
426# since the previous cycle. In addition, a 'resetting' state exists which is
427# similar to 'draining' except that threads leave with a BrokenBarrierError,
428# and a 'broken' state in which all threads get get the exception.
429class Barrier(_Verbose):
430 """
431 Barrier. Useful for synchronizing a fixed number of threads
432 at known synchronization points. Threads block on 'wait()' and are
433 simultaneously once they have all made that call.
434 """
435 def __init__(self, parties, action=None, timeout=None, verbose=None):
436 """
437 Create a barrier, initialised to 'parties' threads.
438 'action' is a callable which, when supplied, will be called
439 by one of the threads after they have all entered the
440 barrier and just prior to releasing them all.
441 If a 'timeout' is provided, it is uses as the default for
442 all subsequent 'wait()' calls.
443 """
444 _Verbose.__init__(self, verbose)
445 self._cond = Condition(Lock())
446 self._action = action
447 self._timeout = timeout
448 self._parties = parties
449 self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
450 self._count = 0
451
452 def wait(self, timeout=None):
453 """
454 Wait for the barrier. When the specified number of threads have
455 started waiting, they are all simultaneously awoken. If an 'action'
456 was provided for the barrier, one of the threads will have executed
457 that callback prior to returning.
458 Returns an individual index number from 0 to 'parties-1'.
459 """
460 if timeout is None:
461 timeout = self._timeout
462 with self._cond:
463 self._enter() # Block while the barrier drains.
464 index = self._count
465 self._count += 1
466 try:
467 if index + 1 == self._parties:
468 # We release the barrier
469 self._release()
470 else:
471 # We wait until someone releases us
472 self._wait(timeout)
473 return index
474 finally:
475 self._count -= 1
476 # Wake up any threads waiting for barrier to drain.
477 self._exit()
478
479 # Block until the barrier is ready for us, or raise an exception
480 # if it is broken.
481 def _enter(self):
482 while self._state in (-1, 1):
483 # It is draining or resetting, wait until done
484 self._cond.wait()
485 #see if the barrier is in a broken state
486 if self._state < 0:
487 raise BrokenBarrierError
488 assert self._state == 0
489
490 # Optionally run the 'action' and release the threads waiting
491 # in the barrier.
492 def _release(self):
493 try:
494 if self._action:
495 self._action()
496 # enter draining state
497 self._state = 1
498 self._cond.notify_all()
499 except:
500 #an exception during the _action handler. Break and reraise
501 self._break()
502 raise
503
504 # Wait in the barrier until we are relased. Raise an exception
505 # if the barrier is reset or broken.
506 def _wait(self, timeout):
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000507 if not self._cond.wait_for(lambda : self._state != 0, timeout):
508 #timed out. Break the barrier
509 self._break()
510 raise BrokenBarrierError
511 if self._state < 0:
512 raise BrokenBarrierError
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000513 assert self._state == 1
514
515 # If we are the last thread to exit the barrier, signal any threads
516 # waiting for the barrier to drain.
517 def _exit(self):
518 if self._count == 0:
519 if self._state in (-1, 1):
520 #resetting or draining
521 self._state = 0
522 self._cond.notify_all()
523
524 def reset(self):
525 """
526 Reset the barrier to the initial state.
527 Any threads currently waiting will get the BrokenBarrier exception
528 raised.
529 """
530 with self._cond:
531 if self._count > 0:
532 if self._state == 0:
533 #reset the barrier, waking up threads
534 self._state = -1
535 elif self._state == -2:
536 #was broken, set it to reset state
537 #which clears when the last thread exits
538 self._state = -1
539 else:
540 self._state = 0
541 self._cond.notify_all()
542
543 def abort(self):
544 """
545 Place the barrier into a 'broken' state.
546 Useful in case of error. Any currently waiting threads and
547 threads attempting to 'wait()' will have BrokenBarrierError
548 raised.
549 """
550 with self._cond:
551 self._break()
552
553 def _break(self):
554 # An internal error was detected. The barrier is set to
555 # a broken state all parties awakened.
556 self._state = -2
557 self._cond.notify_all()
558
559 @property
560 def parties(self):
561 """
562 Return the number of threads required to trip the barrier.
563 """
564 return self._parties
565
566 @property
567 def n_waiting(self):
568 """
569 Return the number of threads that are currently waiting at the barrier.
570 """
571 # We don't need synchronization here since this is an ephemeral result
572 # anyway. It returns the correct value in the steady state.
573 if self._state == 0:
574 return self._count
575 return 0
576
577 @property
578 def broken(self):
579 """
580 Return True if the barrier is in a broken state
581 """
582 return self._state == -2
583
584#exception raised by the Barrier class
585class BrokenBarrierError(RuntimeError): pass
586
587
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000588# Helper to generate new thread names
589_counter = 0
590def _newname(template="Thread-%d"):
591 global _counter
592 _counter = _counter + 1
593 return template % _counter
594
595# Active thread administration
596_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000597_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000598_limbo = {}
599
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200600# For debug and leak testing
601_dangling = WeakSet()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000602
603# Main class for threads
604
605class Thread(_Verbose):
606
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000607 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000608 # Need to store a reference to sys.exc_info for printing
609 # out exceptions when a thread tries to use a global var. during interp.
610 # shutdown and thus raises an exception about trying to perform some
611 # operation on/with a NoneType
612 __exc_info = _sys.exc_info
Christian Heimesbbe741d2008-03-28 10:53:29 +0000613 # Keep sys.exc_clear too to clear the exception just before
614 # allowing .join() to return.
615 #XXX __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000616
617 def __init__(self, group=None, target=None, name=None,
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000618 args=(), kwargs=None, verbose=None, *, daemon=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000619 assert group is None, "group argument must be None for now"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000620 _Verbose.__init__(self, verbose)
Georg Brandla4a8b822005-07-15 09:13:21 +0000621 if kwargs is None:
622 kwargs = {}
Guido van Rossumd0648992007-08-20 19:25:41 +0000623 self._target = target
624 self._name = str(name or _newname())
625 self._args = args
626 self._kwargs = kwargs
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000627 if daemon is not None:
628 self._daemonic = daemon
629 else:
630 self._daemonic = current_thread().daemon
Georg Brandl0c77a822008-06-10 16:37:50 +0000631 self._ident = None
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000632 self._started = Event()
Guido van Rossumd0648992007-08-20 19:25:41 +0000633 self._stopped = False
634 self._block = Condition(Lock())
635 self._initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000636 # sys.stderr is not stored in the class like
637 # sys.exc_info since it can be changed between instances
Guido van Rossumd0648992007-08-20 19:25:41 +0000638 self._stderr = _sys.stderr
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200639 _dangling.add(self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000640
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000641 def _reset_internal_locks(self):
642 # private! Called by _after_fork() to reset our internal locks as
643 # they may be in an invalid state leading to a deadlock or crash.
644 if hasattr(self, '_block'): # DummyThread deletes _block
645 self._block.__init__()
646 self._started._reset_internal_locks()
647
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000648 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000649 assert self._initialized, "Thread.__init__() was not called"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000650 status = "initial"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000651 if self._started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000652 status = "started"
Guido van Rossumd0648992007-08-20 19:25:41 +0000653 if self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000654 status = "stopped"
Guido van Rossumd0648992007-08-20 19:25:41 +0000655 if self._daemonic:
Georg Brandl0c77a822008-06-10 16:37:50 +0000656 status += " daemon"
657 if self._ident is not None:
658 status += " %s" % self._ident
Guido van Rossumd0648992007-08-20 19:25:41 +0000659 return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000660
661 def start(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000662 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000663 raise RuntimeError("thread.__init__() not called")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000664
Benjamin Peterson672b8032008-06-11 19:14:14 +0000665 if self._started.is_set():
Senthil Kumaranfdd4d0f2010-04-06 03:30:18 +0000666 raise RuntimeError("threads can only be started once")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000667 if __debug__:
668 self._note("%s.start(): starting thread", self)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000669 with _active_limbo_lock:
670 _limbo[self] = self
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000671 try:
672 _start_new_thread(self._bootstrap, ())
673 except Exception:
674 with _active_limbo_lock:
675 del _limbo[self]
676 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000677 self._started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000678
679 def run(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000680 try:
681 if self._target:
682 self._target(*self._args, **self._kwargs)
683 finally:
684 # Avoid a refcycle if the thread is running a function with
685 # an argument that has a member that points to the thread.
686 del self._target, self._args, self._kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000687
Guido van Rossumd0648992007-08-20 19:25:41 +0000688 def _bootstrap(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000689 # Wrapper around the real bootstrap code that ignores
690 # exceptions during interpreter cleanup. Those typically
691 # happen when a daemon thread wakes up at an unfortunate
692 # moment, finds the world around it destroyed, and raises some
693 # random exception *** while trying to report the exception in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000694 # _bootstrap_inner() below ***. Those random exceptions
Guido van Rossum61e21b52007-08-20 19:06:03 +0000695 # don't help anybody, and they confuse users, so we suppress
696 # them. We suppress them only when it appears that the world
697 # indeed has already been destroyed, so that exceptions in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000698 # _bootstrap_inner() during normal business hours are properly
Guido van Rossum61e21b52007-08-20 19:06:03 +0000699 # reported. Also, we only suppress them for daemonic threads;
700 # if a non-daemonic encounters this, something else is wrong.
701 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000702 self._bootstrap_inner()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000703 except:
Guido van Rossumd0648992007-08-20 19:25:41 +0000704 if self._daemonic and _sys is None:
Guido van Rossum61e21b52007-08-20 19:06:03 +0000705 return
706 raise
707
Benjamin Petersond23f8222009-04-05 19:13:16 +0000708 def _set_ident(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200709 self._ident = get_ident()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000710
Guido van Rossumd0648992007-08-20 19:25:41 +0000711 def _bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000712 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000713 self._set_ident()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000714 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000715 with _active_limbo_lock:
716 _active[self._ident] = self
717 del _limbo[self]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000718 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000719 self._note("%s._bootstrap(): thread started", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000720
721 if _trace_hook:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000722 self._note("%s._bootstrap(): registering trace hook", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000723 _sys.settrace(_trace_hook)
724 if _profile_hook:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000725 self._note("%s._bootstrap(): registering profile hook", self)
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000726 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000727
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000728 try:
729 self.run()
730 except SystemExit:
731 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000732 self._note("%s._bootstrap(): raised SystemExit", self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000733 except:
734 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000735 self._note("%s._bootstrap(): unhandled exception", self)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000736 # If sys.stderr is no more (most likely from interpreter
Guido van Rossumd0648992007-08-20 19:25:41 +0000737 # shutdown) use self._stderr. Otherwise still use sys (as in
Brett Cannoncc4e9352004-07-03 03:52:35 +0000738 # _sys) in case sys.stderr was redefined since the creation of
739 # self.
740 if _sys:
741 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000742 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000743 else:
744 # Do the best job possible w/o a huge amt. of code to
745 # approximate a traceback (code ideas from
746 # Lib/traceback.py)
Guido van Rossumd0648992007-08-20 19:25:41 +0000747 exc_type, exc_value, exc_tb = self._exc_info()
Brett Cannoncc4e9352004-07-03 03:52:35 +0000748 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000749 print((
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000750 "Exception in thread " + self.name +
Guido van Rossumd0648992007-08-20 19:25:41 +0000751 " (most likely raised during interpreter shutdown):"), file=self._stderr)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000752 print((
Guido van Rossumd0648992007-08-20 19:25:41 +0000753 "Traceback (most recent call last):"), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000754 while exc_tb:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000755 print((
Brett Cannoncc4e9352004-07-03 03:52:35 +0000756 ' File "%s", line %s, in %s' %
757 (exc_tb.tb_frame.f_code.co_filename,
758 exc_tb.tb_lineno,
Guido van Rossumd0648992007-08-20 19:25:41 +0000759 exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000760 exc_tb = exc_tb.tb_next
Guido van Rossumd0648992007-08-20 19:25:41 +0000761 print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000762 # Make sure that exc_tb gets deleted since it is a memory
763 # hog; deleting everything else is just for thoroughness
764 finally:
765 del exc_type, exc_value, exc_tb
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000766 else:
767 if __debug__:
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000768 self._note("%s._bootstrap(): normal return", self)
Christian Heimesbbe741d2008-03-28 10:53:29 +0000769 finally:
770 # Prevent a race in
771 # test_threading.test_no_refcycle_through_target when
772 # the exception keeps the target alive past when we
773 # assert that it's dead.
774 #XXX self.__exc_clear()
775 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000776 finally:
Christian Heimes1af737c2008-01-23 08:24:23 +0000777 with _active_limbo_lock:
778 self._stop()
779 try:
Georg Brandl0c77a822008-06-10 16:37:50 +0000780 # We don't call self._delete() because it also
Christian Heimes1af737c2008-01-23 08:24:23 +0000781 # grabs _active_limbo_lock.
Victor Stinner2a129742011-05-30 23:02:52 +0200782 del _active[get_ident()]
Christian Heimes1af737c2008-01-23 08:24:23 +0000783 except:
784 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000785
Guido van Rossumd0648992007-08-20 19:25:41 +0000786 def _stop(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000787 self._block.acquire()
788 self._stopped = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000789 self._block.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000790 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000791
Guido van Rossumd0648992007-08-20 19:25:41 +0000792 def _delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000793 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000794
Georg Brandl2067bfd2008-05-25 13:05:15 +0000795 # Notes about running with _dummy_thread:
Tim Peters21429932004-07-21 03:36:52 +0000796 #
Georg Brandl2067bfd2008-05-25 13:05:15 +0000797 # Must take care to not raise an exception if _dummy_thread is being
Tim Peters21429932004-07-21 03:36:52 +0000798 # used (and thus this module is being used as an instance of
Georg Brandl2067bfd2008-05-25 13:05:15 +0000799 # dummy_threading). _dummy_thread.get_ident() always returns -1 since
800 # there is only one thread if _dummy_thread is being used. Thus
Tim Peters21429932004-07-21 03:36:52 +0000801 # len(_active) is always <= 1 here, and any Thread instance created
802 # overwrites the (if any) thread currently registered in _active.
803 #
804 # An instance of _MainThread is always created by 'threading'. This
805 # gets overwritten the instant an instance of Thread is created; both
Georg Brandl2067bfd2008-05-25 13:05:15 +0000806 # threads return -1 from _dummy_thread.get_ident() and thus have the
Tim Peters21429932004-07-21 03:36:52 +0000807 # same key in the dict. So when the _MainThread instance created by
808 # 'threading' tries to clean itself up when atexit calls this method
809 # it gets a KeyError if another Thread instance was created.
810 #
811 # This all means that KeyError from trying to delete something from
812 # _active if dummy_threading is being used is a red herring. But
813 # since it isn't if dummy_threading is *not* being used then don't
814 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000815
Christian Heimes969fe572008-01-25 11:23:10 +0000816 try:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000817 with _active_limbo_lock:
Victor Stinner2a129742011-05-30 23:02:52 +0200818 del _active[get_ident()]
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000819 # There must not be any python code between the previous line
820 # and after the lock is released. Otherwise a tracing function
821 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson672b8032008-06-11 19:14:14 +0000822 # current_thread()), and would block.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000823 except KeyError:
824 if 'dummy_threading' not in _sys.modules:
825 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000826
827 def join(self, timeout=None):
Guido van Rossumd0648992007-08-20 19:25:41 +0000828 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000829 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000830 if not self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000831 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000832 if self is current_thread():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000833 raise RuntimeError("cannot join current thread")
834
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000835 if __debug__:
Guido van Rossumd0648992007-08-20 19:25:41 +0000836 if not self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000837 self._note("%s.join(): waiting until thread stops", self)
Christian Heimes969fe572008-01-25 11:23:10 +0000838
839 self._block.acquire()
840 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000841 if timeout is None:
Guido van Rossumd0648992007-08-20 19:25:41 +0000842 while not self._stopped:
843 self._block.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000844 if __debug__:
845 self._note("%s.join(): thread stopped", self)
Brett Cannonad07ff22005-11-23 02:15:50 +0000846 else:
847 deadline = _time() + timeout
Guido van Rossumd0648992007-08-20 19:25:41 +0000848 while not self._stopped:
Brett Cannonad07ff22005-11-23 02:15:50 +0000849 delay = deadline - _time()
850 if delay <= 0:
851 if __debug__:
852 self._note("%s.join(): timed out", self)
853 break
Guido van Rossumd0648992007-08-20 19:25:41 +0000854 self._block.wait(delay)
Brett Cannonad07ff22005-11-23 02:15:50 +0000855 else:
856 if __debug__:
857 self._note("%s.join(): thread stopped", self)
Christian Heimes969fe572008-01-25 11:23:10 +0000858 finally:
859 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000860
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000861 @property
862 def name(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000863 assert self._initialized, "Thread.__init__() not called"
864 return self._name
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000865
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000866 @name.setter
867 def name(self, name):
Guido van Rossumd0648992007-08-20 19:25:41 +0000868 assert self._initialized, "Thread.__init__() not called"
869 self._name = str(name)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000870
Benjamin Peterson773c17b2008-08-18 16:45:31 +0000871 @property
872 def ident(self):
Georg Brandl0c77a822008-06-10 16:37:50 +0000873 assert self._initialized, "Thread.__init__() not called"
874 return self._ident
875
Benjamin Peterson672b8032008-06-11 19:14:14 +0000876 def is_alive(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000877 assert self._initialized, "Thread.__init__() not called"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000878 return self._started.is_set() and not self._stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000879
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000880 isAlive = is_alive
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000881
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000882 @property
883 def daemon(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000884 assert self._initialized, "Thread.__init__() not called"
885 return self._daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000886
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000887 @daemon.setter
888 def daemon(self, daemonic):
Guido van Rossumd0648992007-08-20 19:25:41 +0000889 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000890 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000891 if self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000892 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossumd0648992007-08-20 19:25:41 +0000893 self._daemonic = daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000894
Benjamin Peterson6640d722008-08-18 18:16:46 +0000895 def isDaemon(self):
896 return self.daemon
897
898 def setDaemon(self, daemonic):
899 self.daemon = daemonic
900
901 def getName(self):
902 return self.name
903
904 def setName(self, name):
905 self.name = name
906
Martin v. Löwis44f86962001-09-05 13:44:54 +0000907# The timer class was contributed by Itamar Shtull-Trauring
908
Éric Araujo0cdd4452011-07-28 00:28:28 +0200909class Timer(Thread):
Martin v. Löwis44f86962001-09-05 13:44:54 +0000910 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000911
Martin v. Löwis44f86962001-09-05 13:44:54 +0000912 t = Timer(30.0, f, args=[], kwargs={})
913 t.start()
914 t.cancel() # stop the timer's action if it's still waiting
915 """
Tim Petersb64bec32001-09-18 02:26:39 +0000916
Martin v. Löwis44f86962001-09-05 13:44:54 +0000917 def __init__(self, interval, function, args=[], kwargs={}):
918 Thread.__init__(self)
919 self.interval = interval
920 self.function = function
921 self.args = args
922 self.kwargs = kwargs
923 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000924
Martin v. Löwis44f86962001-09-05 13:44:54 +0000925 def cancel(self):
926 """Stop the timer if it hasn't finished yet"""
927 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000928
Martin v. Löwis44f86962001-09-05 13:44:54 +0000929 def run(self):
930 self.finished.wait(self.interval)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000931 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000932 self.function(*self.args, **self.kwargs)
933 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000934
935# Special thread class to represent the main thread
936# This is garbage collected through an exit handler
937
938class _MainThread(Thread):
939
940 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000941 Thread.__init__(self, name="MainThread", daemon=False)
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000942 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000943 self._set_ident()
944 with _active_limbo_lock:
945 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000946
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000947 def _exitfunc(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000948 self._stop()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000949 t = _pickSomeNonDaemonThread()
950 if t:
951 if __debug__:
952 self._note("%s: waiting for other threads", self)
953 while t:
954 t.join()
955 t = _pickSomeNonDaemonThread()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000956 if __debug__:
957 self._note("%s: exiting", self)
Guido van Rossumd0648992007-08-20 19:25:41 +0000958 self._delete()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000959
960def _pickSomeNonDaemonThread():
961 for t in enumerate():
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000962 if not t.daemon and t.is_alive():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000963 return t
964 return None
965
966
967# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000968# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000969# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000970# leave an entry in the _active dict forever after.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000971# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000972# They are marked as daemon threads so we won't wait for them
973# when we exit (conform previous semantics).
974
975class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000976
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000977 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000978 Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
Tim Peters711906e2005-01-08 07:30:42 +0000979
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000980 # Thread._block consumes an OS-level locking primitive, which
Tim Peters711906e2005-01-08 07:30:42 +0000981 # can never be used by a _DummyThread. Since a _DummyThread
982 # instance is immortal, that's bad, so release this resource.
Guido van Rossumd0648992007-08-20 19:25:41 +0000983 del self._block
Tim Peters711906e2005-01-08 07:30:42 +0000984
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000985 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000986 self._set_ident()
987 with _active_limbo_lock:
988 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000989
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000990 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000991 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000992
993
994# Global API functions
995
Benjamin Peterson672b8032008-06-11 19:14:14 +0000996def current_thread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000997 try:
Victor Stinner2a129742011-05-30 23:02:52 +0200998 return _active[get_ident()]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000999 except KeyError:
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001000 return _DummyThread()
1001
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001002currentThread = current_thread
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001003
Benjamin Peterson672b8032008-06-11 19:14:14 +00001004def active_count():
Benjamin Petersond23f8222009-04-05 19:13:16 +00001005 with _active_limbo_lock:
1006 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001007
Benjamin Petersonb3085c92008-09-01 23:09:31 +00001008activeCount = active_count
Benjamin Petersonf0923f52008-08-18 22:10:13 +00001009
Antoine Pitroubdec11f2009-11-05 13:49:14 +00001010def _enumerate():
1011 # Same as enumerate(), but without the lock. Internal use only.
1012 return list(_active.values()) + list(_limbo.values())
1013
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001014def enumerate():
Benjamin Petersond23f8222009-04-05 19:13:16 +00001015 with _active_limbo_lock:
1016 return list(_active.values()) + list(_limbo.values())
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001017
Georg Brandl2067bfd2008-05-25 13:05:15 +00001018from _thread import stack_size
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001020# Create the main thread object,
1021# and make it available for the interpreter
1022# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001023
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001024_shutdown = _MainThread()._exitfunc
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001025
Jim Fultond15dc062004-07-14 19:11:50 +00001026# get thread-local implementation, either from the thread
1027# module, or from the python fallback
1028
1029try:
Georg Brandl2067bfd2008-05-25 13:05:15 +00001030 from _thread import _local as local
Jim Fultond15dc062004-07-14 19:11:50 +00001031except ImportError:
1032 from _threading_local import local
1033
Guido van Rossum7f5013a1998-04-09 22:01:42 +00001034
Jesse Nollera8513972008-07-17 16:49:17 +00001035def _after_fork():
1036 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
1037 # is called from PyOS_AfterFork. Here we cleanup threading module state
1038 # that should not exist after a fork.
1039
1040 # Reset _active_limbo_lock, in case we forked while the lock was held
1041 # by another (non-forked) thread. http://bugs.python.org/issue874900
1042 global _active_limbo_lock
1043 _active_limbo_lock = _allocate_lock()
1044
1045 # fork() only copied the current thread; clear references to others.
1046 new_active = {}
1047 current = current_thread()
1048 with _active_limbo_lock:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001049 for thread in _active.values():
Jesse Nollera8513972008-07-17 16:49:17 +00001050 if thread is current:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001051 # There is only one active thread. We reset the ident to
1052 # its new value since it can have changed.
Victor Stinner2a129742011-05-30 23:02:52 +02001053 ident = get_ident()
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001054 thread._ident = ident
Gregory P. Smith96c886c2011-01-03 21:06:12 +00001055 # Any condition variables hanging off of the active thread may
1056 # be in an invalid state, so we reinitialize them.
Gregory P. Smith9bd4a242011-01-04 18:33:38 +00001057 thread._reset_internal_locks()
Jesse Nollera8513972008-07-17 16:49:17 +00001058 new_active[ident] = thread
1059 else:
1060 # All the others are already stopped.
1061 # We don't call _Thread__stop() because it tries to acquire
1062 # thread._Thread__block which could also have been held while
1063 # we forked.
Antoine Pitrou5fe291f2008-09-06 23:00:03 +00001064 thread._stopped = True
Jesse Nollera8513972008-07-17 16:49:17 +00001065
1066 _limbo.clear()
1067 _active.clear()
1068 _active.update(new_active)
1069 assert len(_active) == 1