blob: b6d19d584838cc5d9e98d9890d75b94ad241aaa6 [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
Victor Stinnerec895392012-04-29 02:41:27 +02006from time import sleep as _sleep
7try:
8 from time import monotonic as _time
Brett Cannoncd171c82013-07-04 17:43:24 -04009except ImportError:
Victor Stinnerec895392012-04-29 02:41:27 +020010 from time import time as _time
Neil Schemenauerf607fc52003-11-05 23:03:00 +000011from traceback import format_exc as _format_exc
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020012from _weakrefset import WeakSet
Raymond Hettinger30307282013-03-20 19:28:19 -070013from itertools import islice as _islice
Raymond Hettingerec4b1742013-03-10 17:57:28 -070014try:
Raymond Hettingerec4b1742013-03-10 17:57:28 -070015 from _collections import deque as _deque
Brett Cannoncd171c82013-07-04 17:43:24 -040016except ImportError:
Raymond Hettingerec4b1742013-03-10 17:57:28 -070017 from collections import deque as _deque
Guido van Rossum7f5013a1998-04-09 22:01:42 +000018
Benjamin Petersonb3085c92008-09-01 23:09:31 +000019# Note regarding PEP 8 compliant names
20# This threading model was originally inspired by Java, and inherited
21# the convention of camelCase function and method names from that
Ezio Melotti30b9d5d2013-08-17 15:50:46 +030022# language. Those original names are not in any imminent danger of
Benjamin Petersonb3085c92008-09-01 23:09:31 +000023# being deprecated (even for Py3k),so this module provides them as an
24# alias for the PEP 8 compliant names
25# Note that using the new PEP 8 compliant names facilitates substitution
26# with the multiprocessing module, which doesn't provide the old
27# Java inspired names.
28
Benjamin Peterson672b8032008-06-11 19:14:14 +000029__all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000030 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier',
Benjamin Peterson7761b952011-08-02 13:05:47 -050031 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size']
Guido van Rossum7f5013a1998-04-09 22:01:42 +000032
Raymond Hettinger5cee47f2011-01-11 19:59:46 +000033# Rename some stuff so "from threading import *" is safe
Georg Brandl2067bfd2008-05-25 13:05:15 +000034_start_new_thread = _thread.start_new_thread
35_allocate_lock = _thread.allocate_lock
Victor Stinner2a129742011-05-30 23:02:52 +020036get_ident = _thread.get_ident
Georg Brandl2067bfd2008-05-25 13:05:15 +000037ThreadError = _thread.error
Antoine Pitrou434736a2009-11-10 18:46:01 +000038try:
39 _CRLock = _thread.RLock
40except AttributeError:
41 _CRLock = None
Antoine Pitrou7c3e5772010-04-14 15:44:10 +000042TIMEOUT_MAX = _thread.TIMEOUT_MAX
Georg Brandl2067bfd2008-05-25 13:05:15 +000043del _thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +000044
Guido van Rossum7f5013a1998-04-09 22:01:42 +000045
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000046# Support for profile and trace hooks
47
48_profile_hook = None
49_trace_hook = None
50
51def setprofile(func):
52 global _profile_hook
53 _profile_hook = func
Tim Petersd1b108b2003-06-29 17:24:17 +000054
Jeremy Hyltonbfccb352003-06-29 16:58:41 +000055def settrace(func):
56 global _trace_hook
57 _trace_hook = func
Guido van Rossum7f5013a1998-04-09 22:01:42 +000058
59# Synchronization classes
60
61Lock = _allocate_lock
62
Victor Stinner135b6d82012-03-03 01:32:57 +010063def RLock(*args, **kwargs):
64 if _CRLock is None:
65 return _PyRLock(*args, **kwargs)
Antoine Pitrou434736a2009-11-10 18:46:01 +000066 return _CRLock(*args, **kwargs)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000067
Victor Stinner135b6d82012-03-03 01:32:57 +010068class _RLock:
Tim Petersb90f89a2001-01-15 03:26:36 +000069
Victor Stinner135b6d82012-03-03 01:32:57 +010070 def __init__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +000071 self._block = _allocate_lock()
72 self._owner = None
73 self._count = 0
Guido van Rossum7f5013a1998-04-09 22:01:42 +000074
75 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +000076 owner = self._owner
Antoine Pitroub0872682009-11-09 16:08:16 +000077 try:
78 owner = _active[owner].name
79 except KeyError:
80 pass
81 return "<%s owner=%r count=%d>" % (
82 self.__class__.__name__, owner, self._count)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000083
Antoine Pitrou7c3e5772010-04-14 15:44:10 +000084 def acquire(self, blocking=True, timeout=-1):
Victor Stinner2a129742011-05-30 23:02:52 +020085 me = get_ident()
Antoine Pitroub0872682009-11-09 16:08:16 +000086 if self._owner == me:
Raymond Hettinger720da572013-03-10 15:13:35 -070087 self._count += 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +000088 return 1
Antoine Pitrou7c3e5772010-04-14 15:44:10 +000089 rc = self._block.acquire(blocking, timeout)
Guido van Rossum7f5013a1998-04-09 22:01:42 +000090 if rc:
Guido van Rossumd0648992007-08-20 19:25:41 +000091 self._owner = me
92 self._count = 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +000093 return rc
94
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000095 __enter__ = acquire
96
Guido van Rossum7f5013a1998-04-09 22:01:42 +000097 def release(self):
Victor Stinner2a129742011-05-30 23:02:52 +020098 if self._owner != get_ident():
Georg Brandl495f7b52009-10-27 15:28:25 +000099 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000100 self._count = count = self._count - 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000101 if not count:
Guido van Rossumd0648992007-08-20 19:25:41 +0000102 self._owner = None
103 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000104
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000105 def __exit__(self, t, v, tb):
106 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000107
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000108 # Internal methods used by condition variables
109
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000110 def _acquire_restore(self, state):
Guido van Rossumd0648992007-08-20 19:25:41 +0000111 self._block.acquire()
112 self._count, self._owner = state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000113
114 def _release_save(self):
Victor Stinnerc2824d42011-04-24 23:41:33 +0200115 if self._count == 0:
116 raise RuntimeError("cannot release un-acquired lock")
Guido van Rossumd0648992007-08-20 19:25:41 +0000117 count = self._count
118 self._count = 0
119 owner = self._owner
120 self._owner = None
121 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000122 return (count, owner)
123
124 def _is_owned(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200125 return self._owner == get_ident()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000126
Antoine Pitrou434736a2009-11-10 18:46:01 +0000127_PyRLock = _RLock
128
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000129
Victor Stinner135b6d82012-03-03 01:32:57 +0100130class Condition:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000131
Victor Stinner135b6d82012-03-03 01:32:57 +0100132 def __init__(self, lock=None):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000133 if lock is None:
134 lock = RLock()
Guido van Rossumd0648992007-08-20 19:25:41 +0000135 self._lock = lock
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000136 # Export the lock's acquire() and release() methods
137 self.acquire = lock.acquire
138 self.release = lock.release
139 # If the lock defines _release_save() and/or _acquire_restore(),
140 # these override the default implementations (which just call
141 # release() and acquire() on the lock). Ditto for _is_owned().
142 try:
143 self._release_save = lock._release_save
144 except AttributeError:
145 pass
146 try:
147 self._acquire_restore = lock._acquire_restore
148 except AttributeError:
149 pass
150 try:
151 self._is_owned = lock._is_owned
152 except AttributeError:
153 pass
Raymond Hettingerec4b1742013-03-10 17:57:28 -0700154 self._waiters = _deque()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000155
Thomas Wouters477c8d52006-05-27 19:21:47 +0000156 def __enter__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000157 return self._lock.__enter__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000158
Thomas Wouters477c8d52006-05-27 19:21:47 +0000159 def __exit__(self, *args):
Guido van Rossumd0648992007-08-20 19:25:41 +0000160 return self._lock.__exit__(*args)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000161
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000162 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000163 return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000164
165 def _release_save(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000166 self._lock.release() # No state to save
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000167
168 def _acquire_restore(self, x):
Guido van Rossumd0648992007-08-20 19:25:41 +0000169 self._lock.acquire() # Ignore saved state
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000170
171 def _is_owned(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000172 # Return True if lock is owned by current_thread.
Jeremy Hyltonaf7fde72002-08-14 17:43:59 +0000173 # This method is called only if __lock doesn't have _is_owned().
Guido van Rossumd0648992007-08-20 19:25:41 +0000174 if self._lock.acquire(0):
175 self._lock.release()
Tim Petersbc0e9102002-04-04 22:55:58 +0000176 return False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000177 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000178 return True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000179
180 def wait(self, timeout=None):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000181 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000182 raise RuntimeError("cannot wait on un-acquired lock")
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000183 waiter = _allocate_lock()
184 waiter.acquire()
Guido van Rossumd0648992007-08-20 19:25:41 +0000185 self._waiters.append(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000186 saved_state = self._release_save()
Tim Petersc951bf92001-04-02 20:15:57 +0000187 try: # restore state no matter what (e.g., KeyboardInterrupt)
188 if timeout is None:
189 waiter.acquire()
Georg Brandlb9a43912010-10-28 09:03:20 +0000190 gotit = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000191 else:
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000192 if timeout > 0:
193 gotit = waiter.acquire(True, timeout)
194 else:
195 gotit = waiter.acquire(False)
Tim Petersc951bf92001-04-02 20:15:57 +0000196 if not gotit:
Tim Petersc951bf92001-04-02 20:15:57 +0000197 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000198 self._waiters.remove(waiter)
Tim Petersc951bf92001-04-02 20:15:57 +0000199 except ValueError:
200 pass
Georg Brandlb9a43912010-10-28 09:03:20 +0000201 return gotit
Tim Petersc951bf92001-04-02 20:15:57 +0000202 finally:
203 self._acquire_restore(saved_state)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000204
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000205 def wait_for(self, predicate, timeout=None):
206 endtime = None
207 waittime = timeout
208 result = predicate()
209 while not result:
210 if waittime is not None:
211 if endtime is None:
212 endtime = _time() + waittime
213 else:
214 waittime = endtime - _time()
215 if waittime <= 0:
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000216 break
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000217 self.wait(waittime)
218 result = predicate()
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000219 return result
220
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000221 def notify(self, n=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000222 if not self._is_owned():
Georg Brandl495f7b52009-10-27 15:28:25 +0000223 raise RuntimeError("cannot notify on un-acquired lock")
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700224 all_waiters = self._waiters
225 waiters_to_notify = _deque(_islice(all_waiters, n))
226 if not waiters_to_notify:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000227 return
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700228 for waiter in waiters_to_notify:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000229 waiter.release()
230 try:
Raymond Hettingerb65e5792013-03-10 20:34:16 -0700231 all_waiters.remove(waiter)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000232 except ValueError:
233 pass
234
Benjamin Peterson672b8032008-06-11 19:14:14 +0000235 def notify_all(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000236 self.notify(len(self._waiters))
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000237
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000238 notifyAll = notify_all
239
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000240
Victor Stinner135b6d82012-03-03 01:32:57 +0100241class Semaphore:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000242
Andrew M. Kuchling39d3bfc2000-02-29 00:10:24 +0000243 # After Tim Peters' semaphore class, but not quite the same (no maximum)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000244
Victor Stinner135b6d82012-03-03 01:32:57 +0100245 def __init__(self, value=1):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000246 if value < 0:
247 raise ValueError("semaphore initial value must be >= 0")
Guido van Rossumd0648992007-08-20 19:25:41 +0000248 self._cond = Condition(Lock())
249 self._value = value
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000250
Antoine Pitrou0454af92010-04-17 23:51:58 +0000251 def acquire(self, blocking=True, timeout=None):
252 if not blocking and timeout is not None:
253 raise ValueError("can't specify timeout for non-blocking acquire")
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000254 rc = False
Antoine Pitrou0454af92010-04-17 23:51:58 +0000255 endtime = None
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300256 with self._cond:
257 while self._value == 0:
258 if not blocking:
259 break
260 if timeout is not None:
261 if endtime is None:
262 endtime = _time() + timeout
263 else:
264 timeout = endtime - _time()
265 if timeout <= 0:
266 break
267 self._cond.wait(timeout)
268 else:
Serhiy Storchakab00b5962013-04-22 22:54:16 +0300269 self._value -= 1
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300270 rc = True
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000271 return rc
272
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000273 __enter__ = acquire
274
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000275 def release(self):
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300276 with self._cond:
Serhiy Storchakab00b5962013-04-22 22:54:16 +0300277 self._value += 1
Serhiy Storchaka81a58552013-04-22 22:51:43 +0300278 self._cond.notify()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000279
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000280 def __exit__(self, t, v, tb):
281 self.release()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000282
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000283
Éric Araujo0cdd4452011-07-28 00:28:28 +0200284class BoundedSemaphore(Semaphore):
Skip Montanaroe428bb72001-08-20 20:27:58 +0000285 """Semaphore that checks that # releases is <= # acquires"""
Victor Stinner135b6d82012-03-03 01:32:57 +0100286 def __init__(self, value=1):
287 Semaphore.__init__(self, value)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000288 self._initial_value = value
289
290 def release(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000291 if self._value >= self._initial_value:
Collin Winterce36ad82007-08-30 01:19:48 +0000292 raise ValueError("Semaphore released too many times")
Éric Araujo0cdd4452011-07-28 00:28:28 +0200293 return Semaphore.release(self)
Skip Montanaroe428bb72001-08-20 20:27:58 +0000294
295
Victor Stinner135b6d82012-03-03 01:32:57 +0100296class Event:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000297
298 # After Tim Peters' event class (without is_posted())
299
Victor Stinner135b6d82012-03-03 01:32:57 +0100300 def __init__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000301 self._cond = Condition(Lock())
302 self._flag = False
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000303
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000304 def _reset_internal_locks(self):
305 # private! called by Thread._reset_internal_locks by _after_fork()
306 self._cond.__init__()
307
Benjamin Peterson672b8032008-06-11 19:14:14 +0000308 def is_set(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000309 return self._flag
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000310
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000311 isSet = is_set
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000312
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000313 def set(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000314 self._cond.acquire()
315 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000316 self._flag = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000317 self._cond.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000318 finally:
319 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000320
321 def clear(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000322 self._cond.acquire()
323 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000324 self._flag = False
Christian Heimes969fe572008-01-25 11:23:10 +0000325 finally:
326 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000327
328 def wait(self, timeout=None):
Christian Heimes969fe572008-01-25 11:23:10 +0000329 self._cond.acquire()
330 try:
Charles-François Natalided03482012-01-07 18:24:56 +0100331 signaled = self._flag
332 if not signaled:
333 signaled = self._cond.wait(timeout)
334 return signaled
Christian Heimes969fe572008-01-25 11:23:10 +0000335 finally:
336 self._cond.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000337
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000338
339# A barrier class. Inspired in part by the pthread_barrier_* api and
340# the CyclicBarrier class from Java. See
341# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
342# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
343# CyclicBarrier.html
344# for information.
345# We maintain two main states, 'filling' and 'draining' enabling the barrier
346# to be cyclic. Threads are not allowed into it until it has fully drained
347# since the previous cycle. In addition, a 'resetting' state exists which is
348# similar to 'draining' except that threads leave with a BrokenBarrierError,
Ezio Melottie130a522011-10-19 10:58:56 +0300349# and a 'broken' state in which all threads get the exception.
Victor Stinner135b6d82012-03-03 01:32:57 +0100350class Barrier:
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000351 """
352 Barrier. Useful for synchronizing a fixed number of threads
353 at known synchronization points. Threads block on 'wait()' and are
354 simultaneously once they have all made that call.
355 """
Victor Stinner135b6d82012-03-03 01:32:57 +0100356 def __init__(self, parties, action=None, timeout=None):
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000357 """
358 Create a barrier, initialised to 'parties' threads.
359 'action' is a callable which, when supplied, will be called
360 by one of the threads after they have all entered the
361 barrier and just prior to releasing them all.
362 If a 'timeout' is provided, it is uses as the default for
363 all subsequent 'wait()' calls.
364 """
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000365 self._cond = Condition(Lock())
366 self._action = action
367 self._timeout = timeout
368 self._parties = parties
369 self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
370 self._count = 0
371
372 def wait(self, timeout=None):
373 """
374 Wait for the barrier. When the specified number of threads have
375 started waiting, they are all simultaneously awoken. If an 'action'
376 was provided for the barrier, one of the threads will have executed
377 that callback prior to returning.
378 Returns an individual index number from 0 to 'parties-1'.
379 """
380 if timeout is None:
381 timeout = self._timeout
382 with self._cond:
383 self._enter() # Block while the barrier drains.
384 index = self._count
385 self._count += 1
386 try:
387 if index + 1 == self._parties:
388 # We release the barrier
389 self._release()
390 else:
391 # We wait until someone releases us
392 self._wait(timeout)
393 return index
394 finally:
395 self._count -= 1
396 # Wake up any threads waiting for barrier to drain.
397 self._exit()
398
399 # Block until the barrier is ready for us, or raise an exception
400 # if it is broken.
401 def _enter(self):
402 while self._state in (-1, 1):
403 # It is draining or resetting, wait until done
404 self._cond.wait()
405 #see if the barrier is in a broken state
406 if self._state < 0:
407 raise BrokenBarrierError
408 assert self._state == 0
409
410 # Optionally run the 'action' and release the threads waiting
411 # in the barrier.
412 def _release(self):
413 try:
414 if self._action:
415 self._action()
416 # enter draining state
417 self._state = 1
418 self._cond.notify_all()
419 except:
420 #an exception during the _action handler. Break and reraise
421 self._break()
422 raise
423
424 # Wait in the barrier until we are relased. Raise an exception
425 # if the barrier is reset or broken.
426 def _wait(self, timeout):
Kristján Valur Jónsson63315202010-11-18 12:46:39 +0000427 if not self._cond.wait_for(lambda : self._state != 0, timeout):
428 #timed out. Break the barrier
429 self._break()
430 raise BrokenBarrierError
431 if self._state < 0:
432 raise BrokenBarrierError
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000433 assert self._state == 1
434
435 # If we are the last thread to exit the barrier, signal any threads
436 # waiting for the barrier to drain.
437 def _exit(self):
438 if self._count == 0:
439 if self._state in (-1, 1):
440 #resetting or draining
441 self._state = 0
442 self._cond.notify_all()
443
444 def reset(self):
445 """
446 Reset the barrier to the initial state.
447 Any threads currently waiting will get the BrokenBarrier exception
448 raised.
449 """
450 with self._cond:
451 if self._count > 0:
452 if self._state == 0:
453 #reset the barrier, waking up threads
454 self._state = -1
455 elif self._state == -2:
456 #was broken, set it to reset state
457 #which clears when the last thread exits
458 self._state = -1
459 else:
460 self._state = 0
461 self._cond.notify_all()
462
463 def abort(self):
464 """
465 Place the barrier into a 'broken' state.
466 Useful in case of error. Any currently waiting threads and
467 threads attempting to 'wait()' will have BrokenBarrierError
468 raised.
469 """
470 with self._cond:
471 self._break()
472
473 def _break(self):
474 # An internal error was detected. The barrier is set to
475 # a broken state all parties awakened.
476 self._state = -2
477 self._cond.notify_all()
478
479 @property
480 def parties(self):
481 """
482 Return the number of threads required to trip the barrier.
483 """
484 return self._parties
485
486 @property
487 def n_waiting(self):
488 """
489 Return the number of threads that are currently waiting at the barrier.
490 """
491 # We don't need synchronization here since this is an ephemeral result
492 # anyway. It returns the correct value in the steady state.
493 if self._state == 0:
494 return self._count
495 return 0
496
497 @property
498 def broken(self):
499 """
500 Return True if the barrier is in a broken state
501 """
502 return self._state == -2
503
504#exception raised by the Barrier class
505class BrokenBarrierError(RuntimeError): pass
506
507
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000508# Helper to generate new thread names
509_counter = 0
510def _newname(template="Thread-%d"):
511 global _counter
Raymond Hettinger720da572013-03-10 15:13:35 -0700512 _counter += 1
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000513 return template % _counter
514
515# Active thread administration
516_active_limbo_lock = _allocate_lock()
Tim Peters711906e2005-01-08 07:30:42 +0000517_active = {} # maps thread id to Thread object
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000518_limbo = {}
519
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200520# For debug and leak testing
521_dangling = WeakSet()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000522
523# Main class for threads
524
Victor Stinner135b6d82012-03-03 01:32:57 +0100525class Thread:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000526
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000527 __initialized = False
Brett Cannoncc4e9352004-07-03 03:52:35 +0000528 # Need to store a reference to sys.exc_info for printing
529 # out exceptions when a thread tries to use a global var. during interp.
530 # shutdown and thus raises an exception about trying to perform some
531 # operation on/with a NoneType
532 __exc_info = _sys.exc_info
Christian Heimesbbe741d2008-03-28 10:53:29 +0000533 # Keep sys.exc_clear too to clear the exception just before
534 # allowing .join() to return.
535 #XXX __exc_clear = _sys.exc_clear
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000536
537 def __init__(self, group=None, target=None, name=None,
Victor Stinner135b6d82012-03-03 01:32:57 +0100538 args=(), kwargs=None, *, daemon=None):
Guido van Rossum5a43e1a1998-06-09 19:04:26 +0000539 assert group is None, "group argument must be None for now"
Georg Brandla4a8b822005-07-15 09:13:21 +0000540 if kwargs is None:
541 kwargs = {}
Guido van Rossumd0648992007-08-20 19:25:41 +0000542 self._target = target
543 self._name = str(name or _newname())
544 self._args = args
545 self._kwargs = kwargs
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000546 if daemon is not None:
547 self._daemonic = daemon
548 else:
549 self._daemonic = current_thread().daemon
Georg Brandl0c77a822008-06-10 16:37:50 +0000550 self._ident = None
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000551 self._started = Event()
Guido van Rossumd0648992007-08-20 19:25:41 +0000552 self._stopped = False
553 self._block = Condition(Lock())
554 self._initialized = True
Brett Cannoncc4e9352004-07-03 03:52:35 +0000555 # sys.stderr is not stored in the class like
556 # sys.exc_info since it can be changed between instances
Guido van Rossumd0648992007-08-20 19:25:41 +0000557 self._stderr = _sys.stderr
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200558 _dangling.add(self)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000559
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000560 def _reset_internal_locks(self):
561 # private! Called by _after_fork() to reset our internal locks as
562 # they may be in an invalid state leading to a deadlock or crash.
563 if hasattr(self, '_block'): # DummyThread deletes _block
564 self._block.__init__()
565 self._started._reset_internal_locks()
566
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000567 def __repr__(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000568 assert self._initialized, "Thread.__init__() was not called"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000569 status = "initial"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000570 if self._started.is_set():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000571 status = "started"
Guido van Rossumd0648992007-08-20 19:25:41 +0000572 if self._stopped:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000573 status = "stopped"
Guido van Rossumd0648992007-08-20 19:25:41 +0000574 if self._daemonic:
Georg Brandl0c77a822008-06-10 16:37:50 +0000575 status += " daemon"
576 if self._ident is not None:
577 status += " %s" % self._ident
Guido van Rossumd0648992007-08-20 19:25:41 +0000578 return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000579
580 def start(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000581 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000582 raise RuntimeError("thread.__init__() not called")
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000583
Benjamin Peterson672b8032008-06-11 19:14:14 +0000584 if self._started.is_set():
Senthil Kumaranfdd4d0f2010-04-06 03:30:18 +0000585 raise RuntimeError("threads can only be started once")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000586 with _active_limbo_lock:
587 _limbo[self] = self
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000588 try:
589 _start_new_thread(self._bootstrap, ())
590 except Exception:
591 with _active_limbo_lock:
592 del _limbo[self]
593 raise
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000594 self._started.wait()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000595
596 def run(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000597 try:
598 if self._target:
599 self._target(*self._args, **self._kwargs)
600 finally:
601 # Avoid a refcycle if the thread is running a function with
602 # an argument that has a member that points to the thread.
603 del self._target, self._args, self._kwargs
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000604
Guido van Rossumd0648992007-08-20 19:25:41 +0000605 def _bootstrap(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000606 # Wrapper around the real bootstrap code that ignores
607 # exceptions during interpreter cleanup. Those typically
608 # happen when a daemon thread wakes up at an unfortunate
609 # moment, finds the world around it destroyed, and raises some
610 # random exception *** while trying to report the exception in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000611 # _bootstrap_inner() below ***. Those random exceptions
Guido van Rossum61e21b52007-08-20 19:06:03 +0000612 # don't help anybody, and they confuse users, so we suppress
613 # them. We suppress them only when it appears that the world
614 # indeed has already been destroyed, so that exceptions in
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000615 # _bootstrap_inner() during normal business hours are properly
Guido van Rossum61e21b52007-08-20 19:06:03 +0000616 # reported. Also, we only suppress them for daemonic threads;
617 # if a non-daemonic encounters this, something else is wrong.
618 try:
Guido van Rossumd0648992007-08-20 19:25:41 +0000619 self._bootstrap_inner()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000620 except:
Guido van Rossumd0648992007-08-20 19:25:41 +0000621 if self._daemonic and _sys is None:
Guido van Rossum61e21b52007-08-20 19:06:03 +0000622 return
623 raise
624
Benjamin Petersond23f8222009-04-05 19:13:16 +0000625 def _set_ident(self):
Victor Stinner2a129742011-05-30 23:02:52 +0200626 self._ident = get_ident()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000627
Guido van Rossumd0648992007-08-20 19:25:41 +0000628 def _bootstrap_inner(self):
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000629 try:
Benjamin Petersond23f8222009-04-05 19:13:16 +0000630 self._set_ident()
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000631 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000632 with _active_limbo_lock:
633 _active[self._ident] = self
634 del _limbo[self]
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000635
636 if _trace_hook:
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000637 _sys.settrace(_trace_hook)
638 if _profile_hook:
Jeremy Hyltonbfccb352003-06-29 16:58:41 +0000639 _sys.setprofile(_profile_hook)
Tim Petersd1b108b2003-06-29 17:24:17 +0000640
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000641 try:
642 self.run()
643 except SystemExit:
Victor Stinner135b6d82012-03-03 01:32:57 +0100644 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000645 except:
Brett Cannoncc4e9352004-07-03 03:52:35 +0000646 # If sys.stderr is no more (most likely from interpreter
Guido van Rossumd0648992007-08-20 19:25:41 +0000647 # shutdown) use self._stderr. Otherwise still use sys (as in
Brett Cannoncc4e9352004-07-03 03:52:35 +0000648 # _sys) in case sys.stderr was redefined since the creation of
649 # self.
650 if _sys:
651 _sys.stderr.write("Exception in thread %s:\n%s\n" %
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000652 (self.name, _format_exc()))
Brett Cannoncc4e9352004-07-03 03:52:35 +0000653 else:
654 # Do the best job possible w/o a huge amt. of code to
655 # approximate a traceback (code ideas from
656 # Lib/traceback.py)
Guido van Rossumd0648992007-08-20 19:25:41 +0000657 exc_type, exc_value, exc_tb = self._exc_info()
Brett Cannoncc4e9352004-07-03 03:52:35 +0000658 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000659 print((
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000660 "Exception in thread " + self.name +
Guido van Rossumd0648992007-08-20 19:25:41 +0000661 " (most likely raised during interpreter shutdown):"), file=self._stderr)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000662 print((
Guido van Rossumd0648992007-08-20 19:25:41 +0000663 "Traceback (most recent call last):"), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000664 while exc_tb:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000665 print((
Brett Cannoncc4e9352004-07-03 03:52:35 +0000666 ' File "%s", line %s, in %s' %
667 (exc_tb.tb_frame.f_code.co_filename,
668 exc_tb.tb_lineno,
Guido van Rossumd0648992007-08-20 19:25:41 +0000669 exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000670 exc_tb = exc_tb.tb_next
Guido van Rossumd0648992007-08-20 19:25:41 +0000671 print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
Brett Cannoncc4e9352004-07-03 03:52:35 +0000672 # Make sure that exc_tb gets deleted since it is a memory
673 # hog; deleting everything else is just for thoroughness
674 finally:
675 del exc_type, exc_value, exc_tb
Christian Heimesbbe741d2008-03-28 10:53:29 +0000676 finally:
677 # Prevent a race in
678 # test_threading.test_no_refcycle_through_target when
679 # the exception keeps the target alive past when we
680 # assert that it's dead.
681 #XXX self.__exc_clear()
682 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000683 finally:
Christian Heimes1af737c2008-01-23 08:24:23 +0000684 with _active_limbo_lock:
685 self._stop()
686 try:
Georg Brandl0c77a822008-06-10 16:37:50 +0000687 # We don't call self._delete() because it also
Christian Heimes1af737c2008-01-23 08:24:23 +0000688 # grabs _active_limbo_lock.
Victor Stinner2a129742011-05-30 23:02:52 +0200689 del _active[get_ident()]
Christian Heimes1af737c2008-01-23 08:24:23 +0000690 except:
691 pass
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000692
Guido van Rossumd0648992007-08-20 19:25:41 +0000693 def _stop(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000694 self._block.acquire()
695 self._stopped = True
Benjamin Peterson672b8032008-06-11 19:14:14 +0000696 self._block.notify_all()
Christian Heimes969fe572008-01-25 11:23:10 +0000697 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000698
Guido van Rossumd0648992007-08-20 19:25:41 +0000699 def _delete(self):
Tim Peters21429932004-07-21 03:36:52 +0000700 "Remove current thread from the dict of currently running threads."
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000701
Georg Brandl2067bfd2008-05-25 13:05:15 +0000702 # Notes about running with _dummy_thread:
Tim Peters21429932004-07-21 03:36:52 +0000703 #
Georg Brandl2067bfd2008-05-25 13:05:15 +0000704 # Must take care to not raise an exception if _dummy_thread is being
Tim Peters21429932004-07-21 03:36:52 +0000705 # used (and thus this module is being used as an instance of
Georg Brandl2067bfd2008-05-25 13:05:15 +0000706 # dummy_threading). _dummy_thread.get_ident() always returns -1 since
707 # there is only one thread if _dummy_thread is being used. Thus
Tim Peters21429932004-07-21 03:36:52 +0000708 # len(_active) is always <= 1 here, and any Thread instance created
709 # overwrites the (if any) thread currently registered in _active.
710 #
711 # An instance of _MainThread is always created by 'threading'. This
712 # gets overwritten the instant an instance of Thread is created; both
Georg Brandl2067bfd2008-05-25 13:05:15 +0000713 # threads return -1 from _dummy_thread.get_ident() and thus have the
Tim Peters21429932004-07-21 03:36:52 +0000714 # same key in the dict. So when the _MainThread instance created by
715 # 'threading' tries to clean itself up when atexit calls this method
716 # it gets a KeyError if another Thread instance was created.
717 #
718 # This all means that KeyError from trying to delete something from
719 # _active if dummy_threading is being used is a red herring. But
720 # since it isn't if dummy_threading is *not* being used then don't
721 # hide the exception.
Brett Cannon8b3d92a2004-07-21 02:21:58 +0000722
Christian Heimes969fe572008-01-25 11:23:10 +0000723 try:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000724 with _active_limbo_lock:
Victor Stinner2a129742011-05-30 23:02:52 +0200725 del _active[get_ident()]
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000726 # There must not be any python code between the previous line
727 # and after the lock is released. Otherwise a tracing function
728 # could try to acquire the lock again in the same thread, (in
Benjamin Peterson672b8032008-06-11 19:14:14 +0000729 # current_thread()), and would block.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000730 except KeyError:
731 if 'dummy_threading' not in _sys.modules:
732 raise
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000733
734 def join(self, timeout=None):
Guido van Rossumd0648992007-08-20 19:25:41 +0000735 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000736 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000737 if not self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000738 raise RuntimeError("cannot join thread before it is started")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000739 if self is current_thread():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000740 raise RuntimeError("cannot join current thread")
741
Christian Heimes969fe572008-01-25 11:23:10 +0000742 self._block.acquire()
743 try:
Brett Cannonad07ff22005-11-23 02:15:50 +0000744 if timeout is None:
Guido van Rossumd0648992007-08-20 19:25:41 +0000745 while not self._stopped:
746 self._block.wait()
Brett Cannonad07ff22005-11-23 02:15:50 +0000747 else:
748 deadline = _time() + timeout
Guido van Rossumd0648992007-08-20 19:25:41 +0000749 while not self._stopped:
Brett Cannonad07ff22005-11-23 02:15:50 +0000750 delay = deadline - _time()
751 if delay <= 0:
Brett Cannonad07ff22005-11-23 02:15:50 +0000752 break
Guido van Rossumd0648992007-08-20 19:25:41 +0000753 self._block.wait(delay)
Christian Heimes969fe572008-01-25 11:23:10 +0000754 finally:
755 self._block.release()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000756
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000757 @property
758 def name(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000759 assert self._initialized, "Thread.__init__() not called"
760 return self._name
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000761
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000762 @name.setter
763 def name(self, name):
Guido van Rossumd0648992007-08-20 19:25:41 +0000764 assert self._initialized, "Thread.__init__() not called"
765 self._name = str(name)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000766
Benjamin Peterson773c17b2008-08-18 16:45:31 +0000767 @property
768 def ident(self):
Georg Brandl0c77a822008-06-10 16:37:50 +0000769 assert self._initialized, "Thread.__init__() not called"
770 return self._ident
771
Benjamin Peterson672b8032008-06-11 19:14:14 +0000772 def is_alive(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000773 assert self._initialized, "Thread.__init__() not called"
Benjamin Peterson672b8032008-06-11 19:14:14 +0000774 return self._started.is_set() and not self._stopped
Tim Petersb90f89a2001-01-15 03:26:36 +0000775
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000776 isAlive = is_alive
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000777
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000778 @property
779 def daemon(self):
Guido van Rossumd0648992007-08-20 19:25:41 +0000780 assert self._initialized, "Thread.__init__() not called"
781 return self._daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000782
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000783 @daemon.setter
784 def daemon(self, daemonic):
Guido van Rossumd0648992007-08-20 19:25:41 +0000785 if not self._initialized:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000786 raise RuntimeError("Thread.__init__() not called")
Benjamin Peterson672b8032008-06-11 19:14:14 +0000787 if self._started.is_set():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000788 raise RuntimeError("cannot set daemon status of active thread");
Guido van Rossumd0648992007-08-20 19:25:41 +0000789 self._daemonic = daemonic
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000790
Benjamin Peterson6640d722008-08-18 18:16:46 +0000791 def isDaemon(self):
792 return self.daemon
793
794 def setDaemon(self, daemonic):
795 self.daemon = daemonic
796
797 def getName(self):
798 return self.name
799
800 def setName(self, name):
801 self.name = name
802
Martin v. Löwis44f86962001-09-05 13:44:54 +0000803# The timer class was contributed by Itamar Shtull-Trauring
804
Éric Araujo0cdd4452011-07-28 00:28:28 +0200805class Timer(Thread):
Martin v. Löwis44f86962001-09-05 13:44:54 +0000806 """Call a function after a specified number of seconds:
Tim Petersb64bec32001-09-18 02:26:39 +0000807
R David Murray19aeb432013-03-30 17:19:38 -0400808 t = Timer(30.0, f, args=None, kwargs=None)
Martin v. Löwis44f86962001-09-05 13:44:54 +0000809 t.start()
810 t.cancel() # stop the timer's action if it's still waiting
811 """
Tim Petersb64bec32001-09-18 02:26:39 +0000812
R David Murray19aeb432013-03-30 17:19:38 -0400813 def __init__(self, interval, function, args=None, kwargs=None):
Martin v. Löwis44f86962001-09-05 13:44:54 +0000814 Thread.__init__(self)
815 self.interval = interval
816 self.function = function
R David Murray19aeb432013-03-30 17:19:38 -0400817 self.args = args if args is not None else []
818 self.kwargs = kwargs if kwargs is not None else {}
Martin v. Löwis44f86962001-09-05 13:44:54 +0000819 self.finished = Event()
Tim Petersb64bec32001-09-18 02:26:39 +0000820
Martin v. Löwis44f86962001-09-05 13:44:54 +0000821 def cancel(self):
822 """Stop the timer if it hasn't finished yet"""
823 self.finished.set()
Tim Petersb64bec32001-09-18 02:26:39 +0000824
Martin v. Löwis44f86962001-09-05 13:44:54 +0000825 def run(self):
826 self.finished.wait(self.interval)
Benjamin Peterson672b8032008-06-11 19:14:14 +0000827 if not self.finished.is_set():
Martin v. Löwis44f86962001-09-05 13:44:54 +0000828 self.function(*self.args, **self.kwargs)
829 self.finished.set()
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000830
831# Special thread class to represent the main thread
832# This is garbage collected through an exit handler
833
834class _MainThread(Thread):
835
836 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000837 Thread.__init__(self, name="MainThread", daemon=False)
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000838 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000839 self._set_ident()
840 with _active_limbo_lock:
841 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000842
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000843
844# Dummy thread class to represent threads not started here.
Tim Peters711906e2005-01-08 07:30:42 +0000845# These aren't garbage collected when they die, nor can they be waited for.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000846# If they invoke anything in threading.py that calls current_thread(), they
Tim Peters711906e2005-01-08 07:30:42 +0000847# leave an entry in the _active dict forever after.
Benjamin Peterson672b8032008-06-11 19:14:14 +0000848# Their purpose is to return *something* from current_thread().
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000849# They are marked as daemon threads so we won't wait for them
850# when we exit (conform previous semantics).
851
852class _DummyThread(Thread):
Tim Petersb90f89a2001-01-15 03:26:36 +0000853
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000854 def __init__(self):
Antoine Pitrou0bd4deb2011-02-25 22:07:43 +0000855 Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
Tim Peters711906e2005-01-08 07:30:42 +0000856
Gregory P. Smith9bd4a242011-01-04 18:33:38 +0000857 # Thread._block consumes an OS-level locking primitive, which
Tim Peters711906e2005-01-08 07:30:42 +0000858 # can never be used by a _DummyThread. Since a _DummyThread
859 # instance is immortal, that's bad, so release this resource.
Guido van Rossumd0648992007-08-20 19:25:41 +0000860 del self._block
Tim Peters711906e2005-01-08 07:30:42 +0000861
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000862 self._started.set()
Benjamin Petersond23f8222009-04-05 19:13:16 +0000863 self._set_ident()
864 with _active_limbo_lock:
865 _active[self._ident] = self
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000866
Antoine Pitrou8e6e0fd2012-04-19 23:55:01 +0200867 def _stop(self):
868 pass
869
Neal Norwitz45bec8c2002-02-19 03:01:36 +0000870 def join(self, timeout=None):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000871 assert False, "cannot join a dummy thread"
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000872
873
874# Global API functions
875
Benjamin Peterson672b8032008-06-11 19:14:14 +0000876def current_thread():
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000877 try:
Victor Stinner2a129742011-05-30 23:02:52 +0200878 return _active[get_ident()]
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000879 except KeyError:
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000880 return _DummyThread()
881
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000882currentThread = current_thread
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000883
Benjamin Peterson672b8032008-06-11 19:14:14 +0000884def active_count():
Benjamin Petersond23f8222009-04-05 19:13:16 +0000885 with _active_limbo_lock:
886 return len(_active) + len(_limbo)
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000887
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000888activeCount = active_count
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000889
Antoine Pitroubdec11f2009-11-05 13:49:14 +0000890def _enumerate():
891 # Same as enumerate(), but without the lock. Internal use only.
892 return list(_active.values()) + list(_limbo.values())
893
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000894def enumerate():
Benjamin Petersond23f8222009-04-05 19:13:16 +0000895 with _active_limbo_lock:
896 return list(_active.values()) + list(_limbo.values())
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000897
Georg Brandl2067bfd2008-05-25 13:05:15 +0000898from _thread import stack_size
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000899
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000900# Create the main thread object,
901# and make it available for the interpreter
902# (Py_Main) as threading._shutdown.
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000903
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300904_main_thread = _MainThread()
905
906def _shutdown():
907 _main_thread._stop()
908 t = _pickSomeNonDaemonThread()
909 while t:
910 t.join()
911 t = _pickSomeNonDaemonThread()
912 _main_thread._delete()
913
914def _pickSomeNonDaemonThread():
915 for t in enumerate():
916 if not t.daemon and t.is_alive():
917 return t
918 return None
919
920def main_thread():
Andrew Svetlovb1dd5572013-09-04 10:33:11 +0300921 """Return the main thread object.
922
923 In normal conditions, the main thread is the thread from which the
924 Python interpreter was started.
925 """
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300926 return _main_thread
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000927
Jim Fultond15dc062004-07-14 19:11:50 +0000928# get thread-local implementation, either from the thread
929# module, or from the python fallback
930
931try:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000932 from _thread import _local as local
Brett Cannoncd171c82013-07-04 17:43:24 -0400933except ImportError:
Jim Fultond15dc062004-07-14 19:11:50 +0000934 from _threading_local import local
935
Guido van Rossum7f5013a1998-04-09 22:01:42 +0000936
Jesse Nollera8513972008-07-17 16:49:17 +0000937def _after_fork():
938 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
939 # is called from PyOS_AfterFork. Here we cleanup threading module state
940 # that should not exist after a fork.
941
942 # Reset _active_limbo_lock, in case we forked while the lock was held
943 # by another (non-forked) thread. http://bugs.python.org/issue874900
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300944 global _active_limbo_lock, _main_thread
Jesse Nollera8513972008-07-17 16:49:17 +0000945 _active_limbo_lock = _allocate_lock()
946
947 # fork() only copied the current thread; clear references to others.
948 new_active = {}
949 current = current_thread()
Andrew Svetlov58b5c5a2013-09-04 07:01:07 +0300950 _main_thread = current
Jesse Nollera8513972008-07-17 16:49:17 +0000951 with _active_limbo_lock:
Charles-François Natali9939cc82013-08-30 23:32:53 +0200952 for thread in _enumerate():
Charles-François Natalib055bf62011-12-18 18:45:16 +0100953 # Any lock/condition variable may be currently locked or in an
954 # invalid state, so we reinitialize them.
955 thread._reset_internal_locks()
Jesse Nollera8513972008-07-17 16:49:17 +0000956 if thread is current:
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000957 # There is only one active thread. We reset the ident to
958 # its new value since it can have changed.
Victor Stinner2a129742011-05-30 23:02:52 +0200959 ident = get_ident()
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000960 thread._ident = ident
Jesse Nollera8513972008-07-17 16:49:17 +0000961 new_active[ident] = thread
962 else:
963 # All the others are already stopped.
Charles-François Natalib055bf62011-12-18 18:45:16 +0100964 thread._stop()
Jesse Nollera8513972008-07-17 16:49:17 +0000965
966 _limbo.clear()
967 _active.clear()
968 _active.update(new_active)
969 assert len(_active) == 1