Jeremy Hylton | 92bb6e7 | 2002-08-14 19:25:42 +0000 | [diff] [blame] | 1 | """Thread module emulating a subset of Java's threading model.""" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 2 | |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 3 | import sys as _sys |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 4 | import _thread |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 5 | |
Victor Stinner | ec89539 | 2012-04-29 02:41:27 +0200 | [diff] [blame] | 6 | try: |
| 7 | from time import monotonic as _time |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 8 | except ImportError: |
Victor Stinner | ec89539 | 2012-04-29 02:41:27 +0200 | [diff] [blame] | 9 | from time import time as _time |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 10 | from traceback import format_exc as _format_exc |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 11 | from _weakrefset import WeakSet |
R David Murray | b186f1df | 2014-10-04 17:43:54 -0400 | [diff] [blame] | 12 | from itertools import islice as _islice, count as _count |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 13 | try: |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 14 | from _collections import deque as _deque |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 15 | except ImportError: |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 16 | from collections import deque as _deque |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 17 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 18 | # Note regarding PEP 8 compliant names |
| 19 | # This threading model was originally inspired by Java, and inherited |
| 20 | # the convention of camelCase function and method names from that |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 21 | # language. Those original names are not in any imminent danger of |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 22 | # being deprecated (even for Py3k),so this module provides them as an |
| 23 | # alias for the PEP 8 compliant names |
| 24 | # Note that using the new PEP 8 compliant names facilitates substitution |
| 25 | # with the multiprocessing module, which doesn't provide the old |
| 26 | # Java inspired names. |
| 27 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 28 | __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event', |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 29 | 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', |
Benjamin Peterson | 7761b95 | 2011-08-02 13:05:47 -0500 | [diff] [blame] | 30 | 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 31 | |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 32 | # Rename some stuff so "from threading import *" is safe |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 33 | _start_new_thread = _thread.start_new_thread |
| 34 | _allocate_lock = _thread.allocate_lock |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 35 | _set_sentinel = _thread._set_sentinel |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 36 | get_ident = _thread.get_ident |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 37 | ThreadError = _thread.error |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 38 | try: |
| 39 | _CRLock = _thread.RLock |
| 40 | except AttributeError: |
| 41 | _CRLock = None |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 42 | TIMEOUT_MAX = _thread.TIMEOUT_MAX |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 43 | del _thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 44 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 45 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 46 | # Support for profile and trace hooks |
| 47 | |
| 48 | _profile_hook = None |
| 49 | _trace_hook = None |
| 50 | |
| 51 | def setprofile(func): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 52 | """Set a profile function for all threads started from the threading module. |
| 53 | |
| 54 | The func will be passed to sys.setprofile() for each thread, before its |
| 55 | run() method is called. |
| 56 | |
| 57 | """ |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 58 | global _profile_hook |
| 59 | _profile_hook = func |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 60 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 61 | def settrace(func): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 62 | """Set a trace function for all threads started from the threading module. |
| 63 | |
| 64 | The func will be passed to sys.settrace() for each thread, before its run() |
| 65 | method is called. |
| 66 | |
| 67 | """ |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 68 | global _trace_hook |
| 69 | _trace_hook = func |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 70 | |
| 71 | # Synchronization classes |
| 72 | |
| 73 | Lock = _allocate_lock |
| 74 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 75 | def RLock(*args, **kwargs): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 76 | """Factory function that returns a new reentrant lock. |
| 77 | |
| 78 | A reentrant lock must be released by the thread that acquired it. Once a |
| 79 | thread has acquired a reentrant lock, the same thread may acquire it again |
| 80 | without blocking; the thread must release it once for each time it has |
| 81 | acquired it. |
| 82 | |
| 83 | """ |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 84 | if _CRLock is None: |
| 85 | return _PyRLock(*args, **kwargs) |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 86 | return _CRLock(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 87 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 88 | class _RLock: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 89 | """This class implements reentrant lock objects. |
| 90 | |
| 91 | A reentrant lock must be released by the thread that acquired it. Once a |
| 92 | thread has acquired a reentrant lock, the same thread may acquire it |
| 93 | again without blocking; the thread must release it once for each time it |
| 94 | has acquired it. |
| 95 | |
| 96 | """ |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 97 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 98 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 99 | self._block = _allocate_lock() |
| 100 | self._owner = None |
| 101 | self._count = 0 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 102 | |
| 103 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 104 | owner = self._owner |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 105 | try: |
| 106 | owner = _active[owner].name |
| 107 | except KeyError: |
| 108 | pass |
| 109 | return "<%s owner=%r count=%d>" % ( |
| 110 | self.__class__.__name__, owner, self._count) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 111 | |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 112 | def acquire(self, blocking=True, timeout=-1): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 113 | """Acquire a lock, blocking or non-blocking. |
| 114 | |
| 115 | When invoked without arguments: if this thread already owns the lock, |
| 116 | increment the recursion level by one, and return immediately. Otherwise, |
| 117 | if another thread owns the lock, block until the lock is unlocked. Once |
| 118 | the lock is unlocked (not owned by any thread), then grab ownership, set |
| 119 | the recursion level to one, and return. If more than one thread is |
| 120 | blocked waiting until the lock is unlocked, only one at a time will be |
| 121 | able to grab ownership of the lock. There is no return value in this |
| 122 | case. |
| 123 | |
| 124 | When invoked with the blocking argument set to true, do the same thing |
| 125 | as when called without arguments, and return true. |
| 126 | |
| 127 | When invoked with the blocking argument set to false, do not block. If a |
| 128 | call without an argument would block, return false immediately; |
| 129 | otherwise, do the same thing as when called without arguments, and |
| 130 | return true. |
| 131 | |
| 132 | When invoked with the floating-point timeout argument set to a positive |
| 133 | value, block for at most the number of seconds specified by timeout |
| 134 | and as long as the lock cannot be acquired. Return true if the lock has |
| 135 | been acquired, false if the timeout has elapsed. |
| 136 | |
| 137 | """ |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 138 | me = get_ident() |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 139 | if self._owner == me: |
Raymond Hettinger | 720da57 | 2013-03-10 15:13:35 -0700 | [diff] [blame] | 140 | self._count += 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 141 | return 1 |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 142 | rc = self._block.acquire(blocking, timeout) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 143 | if rc: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 144 | self._owner = me |
| 145 | self._count = 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 146 | return rc |
| 147 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 148 | __enter__ = acquire |
| 149 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 150 | def release(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 151 | """Release a lock, decrementing the recursion level. |
| 152 | |
| 153 | If after the decrement it is zero, reset the lock to unlocked (not owned |
| 154 | by any thread), and if any other threads are blocked waiting for the |
| 155 | lock to become unlocked, allow exactly one of them to proceed. If after |
| 156 | the decrement the recursion level is still nonzero, the lock remains |
| 157 | locked and owned by the calling thread. |
| 158 | |
| 159 | Only call this method when the calling thread owns the lock. A |
| 160 | RuntimeError is raised if this method is called when the lock is |
| 161 | unlocked. |
| 162 | |
| 163 | There is no return value. |
| 164 | |
| 165 | """ |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 166 | if self._owner != get_ident(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 167 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 168 | self._count = count = self._count - 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 169 | if not count: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 170 | self._owner = None |
| 171 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 172 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 173 | def __exit__(self, t, v, tb): |
| 174 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 175 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 176 | # Internal methods used by condition variables |
| 177 | |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 178 | def _acquire_restore(self, state): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 179 | self._block.acquire() |
| 180 | self._count, self._owner = state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 181 | |
| 182 | def _release_save(self): |
Victor Stinner | c2824d4 | 2011-04-24 23:41:33 +0200 | [diff] [blame] | 183 | if self._count == 0: |
| 184 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 185 | count = self._count |
| 186 | self._count = 0 |
| 187 | owner = self._owner |
| 188 | self._owner = None |
| 189 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 190 | return (count, owner) |
| 191 | |
| 192 | def _is_owned(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 193 | return self._owner == get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 194 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 195 | _PyRLock = _RLock |
| 196 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 197 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 198 | class Condition: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 199 | """Class that implements a condition variable. |
| 200 | |
| 201 | A condition variable allows one or more threads to wait until they are |
| 202 | notified by another thread. |
| 203 | |
| 204 | If the lock argument is given and not None, it must be a Lock or RLock |
| 205 | object, and it is used as the underlying lock. Otherwise, a new RLock object |
| 206 | is created and used as the underlying lock. |
| 207 | |
| 208 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 209 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 210 | def __init__(self, lock=None): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 211 | if lock is None: |
| 212 | lock = RLock() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 213 | self._lock = lock |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 214 | # Export the lock's acquire() and release() methods |
| 215 | self.acquire = lock.acquire |
| 216 | self.release = lock.release |
| 217 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 218 | # these override the default implementations (which just call |
| 219 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 220 | try: |
| 221 | self._release_save = lock._release_save |
| 222 | except AttributeError: |
| 223 | pass |
| 224 | try: |
| 225 | self._acquire_restore = lock._acquire_restore |
| 226 | except AttributeError: |
| 227 | pass |
| 228 | try: |
| 229 | self._is_owned = lock._is_owned |
| 230 | except AttributeError: |
| 231 | pass |
Raymond Hettinger | ec4b174 | 2013-03-10 17:57:28 -0700 | [diff] [blame] | 232 | self._waiters = _deque() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 233 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 234 | def __enter__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 235 | return self._lock.__enter__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 236 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 237 | def __exit__(self, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 238 | return self._lock.__exit__(*args) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 239 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 240 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 241 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 242 | |
| 243 | def _release_save(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 244 | self._lock.release() # No state to save |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 245 | |
| 246 | def _acquire_restore(self, x): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 247 | self._lock.acquire() # Ignore saved state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 248 | |
| 249 | def _is_owned(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 250 | # Return True if lock is owned by current_thread. |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 251 | # This method is called only if _lock doesn't have _is_owned(). |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 252 | if self._lock.acquire(0): |
| 253 | self._lock.release() |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 254 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 255 | else: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 256 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 257 | |
| 258 | def wait(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 259 | """Wait until notified or until a timeout occurs. |
| 260 | |
| 261 | If the calling thread has not acquired the lock when this method is |
| 262 | called, a RuntimeError is raised. |
| 263 | |
| 264 | This method releases the underlying lock, and then blocks until it is |
| 265 | awakened by a notify() or notify_all() call for the same condition |
| 266 | variable in another thread, or until the optional timeout occurs. Once |
| 267 | awakened or timed out, it re-acquires the lock and returns. |
| 268 | |
| 269 | When the timeout argument is present and not None, it should be a |
| 270 | floating point number specifying a timeout for the operation in seconds |
| 271 | (or fractions thereof). |
| 272 | |
| 273 | When the underlying lock is an RLock, it is not released using its |
| 274 | release() method, since this may not actually unlock the lock when it |
| 275 | was acquired multiple times recursively. Instead, an internal interface |
| 276 | of the RLock class is used, which really unlocks it even when it has |
| 277 | been recursively acquired several times. Another internal interface is |
| 278 | then used to restore the recursion level when the lock is reacquired. |
| 279 | |
| 280 | """ |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 281 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 282 | raise RuntimeError("cannot wait on un-acquired lock") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 283 | waiter = _allocate_lock() |
| 284 | waiter.acquire() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 285 | self._waiters.append(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 286 | saved_state = self._release_save() |
Antoine Pitrou | a64b92e | 2014-08-29 23:26:36 +0200 | [diff] [blame] | 287 | gotit = False |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 288 | try: # restore state no matter what (e.g., KeyboardInterrupt) |
| 289 | if timeout is None: |
| 290 | waiter.acquire() |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 291 | gotit = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 292 | else: |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 293 | if timeout > 0: |
| 294 | gotit = waiter.acquire(True, timeout) |
| 295 | else: |
| 296 | gotit = waiter.acquire(False) |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 297 | return gotit |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 298 | finally: |
| 299 | self._acquire_restore(saved_state) |
Antoine Pitrou | a64b92e | 2014-08-29 23:26:36 +0200 | [diff] [blame] | 300 | if not gotit: |
| 301 | try: |
| 302 | self._waiters.remove(waiter) |
| 303 | except ValueError: |
| 304 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 305 | |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 306 | def wait_for(self, predicate, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 307 | """Wait until a condition evaluates to True. |
| 308 | |
| 309 | predicate should be a callable which result will be interpreted as a |
| 310 | boolean value. A timeout may be provided giving the maximum time to |
| 311 | wait. |
| 312 | |
| 313 | """ |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 314 | endtime = None |
| 315 | waittime = timeout |
| 316 | result = predicate() |
| 317 | while not result: |
| 318 | if waittime is not None: |
| 319 | if endtime is None: |
| 320 | endtime = _time() + waittime |
| 321 | else: |
| 322 | waittime = endtime - _time() |
| 323 | if waittime <= 0: |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 324 | break |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 325 | self.wait(waittime) |
| 326 | result = predicate() |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 327 | return result |
| 328 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 329 | def notify(self, n=1): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 330 | """Wake up one or more threads waiting on this condition, if any. |
| 331 | |
| 332 | If the calling thread has not acquired the lock when this method is |
| 333 | called, a RuntimeError is raised. |
| 334 | |
| 335 | This method wakes up at most n of the threads waiting for the condition |
| 336 | variable; it is a no-op if no threads are waiting. |
| 337 | |
| 338 | """ |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 339 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 340 | raise RuntimeError("cannot notify on un-acquired lock") |
Raymond Hettinger | b65e579 | 2013-03-10 20:34:16 -0700 | [diff] [blame] | 341 | all_waiters = self._waiters |
| 342 | waiters_to_notify = _deque(_islice(all_waiters, n)) |
| 343 | if not waiters_to_notify: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 344 | return |
Raymond Hettinger | b65e579 | 2013-03-10 20:34:16 -0700 | [diff] [blame] | 345 | for waiter in waiters_to_notify: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 346 | waiter.release() |
| 347 | try: |
Raymond Hettinger | b65e579 | 2013-03-10 20:34:16 -0700 | [diff] [blame] | 348 | all_waiters.remove(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 349 | except ValueError: |
| 350 | pass |
| 351 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 352 | def notify_all(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 353 | """Wake up all threads waiting on this condition. |
| 354 | |
| 355 | If the calling thread has not acquired the lock when this method |
| 356 | is called, a RuntimeError is raised. |
| 357 | |
| 358 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 359 | self.notify(len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 360 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 361 | notifyAll = notify_all |
| 362 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 363 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 364 | class Semaphore: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 365 | """This class implements semaphore objects. |
| 366 | |
| 367 | Semaphores manage a counter representing the number of release() calls minus |
| 368 | the number of acquire() calls, plus an initial value. The acquire() method |
| 369 | blocks if necessary until it can return without making the counter |
| 370 | negative. If not given, value defaults to 1. |
| 371 | |
| 372 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 373 | |
Andrew M. Kuchling | 39d3bfc | 2000-02-29 00:10:24 +0000 | [diff] [blame] | 374 | # After Tim Peters' semaphore class, but not quite the same (no maximum) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 375 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 376 | def __init__(self, value=1): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 377 | if value < 0: |
| 378 | raise ValueError("semaphore initial value must be >= 0") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 379 | self._cond = Condition(Lock()) |
| 380 | self._value = value |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 381 | |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 382 | def acquire(self, blocking=True, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 383 | """Acquire a semaphore, decrementing the internal counter by one. |
| 384 | |
| 385 | When invoked without arguments: if the internal counter is larger than |
| 386 | zero on entry, decrement it by one and return immediately. If it is zero |
| 387 | on entry, block, waiting until some other thread has called release() to |
| 388 | make it larger than zero. This is done with proper interlocking so that |
| 389 | if multiple acquire() calls are blocked, release() will wake exactly one |
| 390 | of them up. The implementation may pick one at random, so the order in |
| 391 | which blocked threads are awakened should not be relied on. There is no |
| 392 | return value in this case. |
| 393 | |
| 394 | When invoked with blocking set to true, do the same thing as when called |
| 395 | without arguments, and return true. |
| 396 | |
| 397 | When invoked with blocking set to false, do not block. If a call without |
| 398 | an argument would block, return false immediately; otherwise, do the |
| 399 | same thing as when called without arguments, and return true. |
| 400 | |
| 401 | When invoked with a timeout other than None, it will block for at |
| 402 | most timeout seconds. If acquire does not complete successfully in |
| 403 | that interval, return false. Return true otherwise. |
| 404 | |
| 405 | """ |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 406 | if not blocking and timeout is not None: |
| 407 | raise ValueError("can't specify timeout for non-blocking acquire") |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 408 | rc = False |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 409 | endtime = None |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 410 | with self._cond: |
| 411 | while self._value == 0: |
| 412 | if not blocking: |
| 413 | break |
| 414 | if timeout is not None: |
| 415 | if endtime is None: |
| 416 | endtime = _time() + timeout |
| 417 | else: |
| 418 | timeout = endtime - _time() |
| 419 | if timeout <= 0: |
| 420 | break |
| 421 | self._cond.wait(timeout) |
| 422 | else: |
Serhiy Storchaka | b00b596 | 2013-04-22 22:54:16 +0300 | [diff] [blame] | 423 | self._value -= 1 |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 424 | rc = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 425 | return rc |
| 426 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 427 | __enter__ = acquire |
| 428 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 429 | def release(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 430 | """Release a semaphore, incrementing the internal counter by one. |
| 431 | |
| 432 | When the counter is zero on entry and another thread is waiting for it |
| 433 | to become larger than zero again, wake up that thread. |
| 434 | |
| 435 | """ |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 436 | with self._cond: |
Serhiy Storchaka | b00b596 | 2013-04-22 22:54:16 +0300 | [diff] [blame] | 437 | self._value += 1 |
Serhiy Storchaka | 81a5855 | 2013-04-22 22:51:43 +0300 | [diff] [blame] | 438 | self._cond.notify() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 439 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 440 | def __exit__(self, t, v, tb): |
| 441 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 442 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 443 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 444 | class BoundedSemaphore(Semaphore): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 445 | """Implements a bounded semaphore. |
| 446 | |
| 447 | A bounded semaphore checks to make sure its current value doesn't exceed its |
| 448 | initial value. If it does, ValueError is raised. In most situations |
| 449 | semaphores are used to guard resources with limited capacity. |
| 450 | |
| 451 | If the semaphore is released too many times it's a sign of a bug. If not |
| 452 | given, value defaults to 1. |
| 453 | |
| 454 | Like regular semaphores, bounded semaphores manage a counter representing |
| 455 | the number of release() calls minus the number of acquire() calls, plus an |
| 456 | initial value. The acquire() method blocks if necessary until it can return |
| 457 | without making the counter negative. If not given, value defaults to 1. |
| 458 | |
| 459 | """ |
| 460 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 461 | def __init__(self, value=1): |
| 462 | Semaphore.__init__(self, value) |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 463 | self._initial_value = value |
| 464 | |
| 465 | def release(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 466 | """Release a semaphore, incrementing the internal counter by one. |
| 467 | |
| 468 | When the counter is zero on entry and another thread is waiting for it |
| 469 | to become larger than zero again, wake up that thread. |
| 470 | |
| 471 | If the number of releases exceeds the number of acquires, |
| 472 | raise a ValueError. |
| 473 | |
| 474 | """ |
Tim Peters | 7634e1c | 2013-10-08 20:55:51 -0500 | [diff] [blame] | 475 | with self._cond: |
| 476 | if self._value >= self._initial_value: |
| 477 | raise ValueError("Semaphore released too many times") |
| 478 | self._value += 1 |
| 479 | self._cond.notify() |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 480 | |
| 481 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 482 | class Event: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 483 | """Class implementing event objects. |
| 484 | |
| 485 | Events manage a flag that can be set to true with the set() method and reset |
| 486 | to false with the clear() method. The wait() method blocks until the flag is |
| 487 | true. The flag is initially false. |
| 488 | |
| 489 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 490 | |
| 491 | # After Tim Peters' event class (without is_posted()) |
| 492 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 493 | def __init__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 494 | self._cond = Condition(Lock()) |
| 495 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 496 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 497 | def _reset_internal_locks(self): |
| 498 | # private! called by Thread._reset_internal_locks by _after_fork() |
Benjamin Peterson | 15982aa | 2015-10-05 21:56:22 -0700 | [diff] [blame] | 499 | self._cond.__init__(Lock()) |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 500 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 501 | def is_set(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 502 | """Return true if and only if the internal flag is true.""" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 503 | return self._flag |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 504 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 505 | isSet = is_set |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 506 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 507 | def set(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 508 | """Set the internal flag to true. |
| 509 | |
| 510 | All threads waiting for it to become true are awakened. Threads |
| 511 | that call wait() once the flag is true will not block at all. |
| 512 | |
| 513 | """ |
Benjamin Peterson | 414918a | 2015-10-10 19:34:46 -0700 | [diff] [blame] | 514 | with self._cond: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 515 | self._flag = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 516 | self._cond.notify_all() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 517 | |
| 518 | def clear(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 519 | """Reset the internal flag to false. |
| 520 | |
| 521 | Subsequently, threads calling wait() will block until set() is called to |
| 522 | set the internal flag to true again. |
| 523 | |
| 524 | """ |
Benjamin Peterson | 414918a | 2015-10-10 19:34:46 -0700 | [diff] [blame] | 525 | with self._cond: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 526 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 527 | |
| 528 | def wait(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 529 | """Block until the internal flag is true. |
| 530 | |
| 531 | If the internal flag is true on entry, return immediately. Otherwise, |
| 532 | block until another thread calls set() to set the flag to true, or until |
| 533 | the optional timeout occurs. |
| 534 | |
| 535 | When the timeout argument is present and not None, it should be a |
| 536 | floating point number specifying a timeout for the operation in seconds |
| 537 | (or fractions thereof). |
| 538 | |
| 539 | This method returns the internal flag on exit, so it will always return |
| 540 | True except if a timeout is given and the operation times out. |
| 541 | |
| 542 | """ |
Benjamin Peterson | 414918a | 2015-10-10 19:34:46 -0700 | [diff] [blame] | 543 | with self._cond: |
Charles-François Natali | ded0348 | 2012-01-07 18:24:56 +0100 | [diff] [blame] | 544 | signaled = self._flag |
| 545 | if not signaled: |
| 546 | signaled = self._cond.wait(timeout) |
| 547 | return signaled |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 548 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 549 | |
| 550 | # A barrier class. Inspired in part by the pthread_barrier_* api and |
| 551 | # the CyclicBarrier class from Java. See |
| 552 | # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and |
| 553 | # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ |
| 554 | # CyclicBarrier.html |
| 555 | # for information. |
| 556 | # We maintain two main states, 'filling' and 'draining' enabling the barrier |
| 557 | # to be cyclic. Threads are not allowed into it until it has fully drained |
| 558 | # since the previous cycle. In addition, a 'resetting' state exists which is |
| 559 | # similar to 'draining' except that threads leave with a BrokenBarrierError, |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 560 | # and a 'broken' state in which all threads get the exception. |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 561 | class Barrier: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 562 | """Implements a Barrier. |
| 563 | |
| 564 | Useful for synchronizing a fixed number of threads at known synchronization |
| 565 | points. Threads block on 'wait()' and are simultaneously once they have all |
| 566 | made that call. |
| 567 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 568 | """ |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 569 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 570 | def __init__(self, parties, action=None, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 571 | """Create a barrier, initialised to 'parties' threads. |
| 572 | |
| 573 | 'action' is a callable which, when supplied, will be called by one of |
| 574 | the threads after they have all entered the barrier and just prior to |
| 575 | releasing them all. If a 'timeout' is provided, it is uses as the |
| 576 | default for all subsequent 'wait()' calls. |
| 577 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 578 | """ |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 579 | self._cond = Condition(Lock()) |
| 580 | self._action = action |
| 581 | self._timeout = timeout |
| 582 | self._parties = parties |
| 583 | self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken |
| 584 | self._count = 0 |
| 585 | |
| 586 | def wait(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 587 | """Wait for the barrier. |
| 588 | |
| 589 | When the specified number of threads have started waiting, they are all |
| 590 | simultaneously awoken. If an 'action' was provided for the barrier, one |
| 591 | of the threads will have executed that callback prior to returning. |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 592 | Returns an individual index number from 0 to 'parties-1'. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 593 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 594 | """ |
| 595 | if timeout is None: |
| 596 | timeout = self._timeout |
| 597 | with self._cond: |
| 598 | self._enter() # Block while the barrier drains. |
| 599 | index = self._count |
| 600 | self._count += 1 |
| 601 | try: |
| 602 | if index + 1 == self._parties: |
| 603 | # We release the barrier |
| 604 | self._release() |
| 605 | else: |
| 606 | # We wait until someone releases us |
| 607 | self._wait(timeout) |
| 608 | return index |
| 609 | finally: |
| 610 | self._count -= 1 |
| 611 | # Wake up any threads waiting for barrier to drain. |
| 612 | self._exit() |
| 613 | |
| 614 | # Block until the barrier is ready for us, or raise an exception |
| 615 | # if it is broken. |
| 616 | def _enter(self): |
| 617 | while self._state in (-1, 1): |
| 618 | # It is draining or resetting, wait until done |
| 619 | self._cond.wait() |
| 620 | #see if the barrier is in a broken state |
| 621 | if self._state < 0: |
| 622 | raise BrokenBarrierError |
| 623 | assert self._state == 0 |
| 624 | |
| 625 | # Optionally run the 'action' and release the threads waiting |
| 626 | # in the barrier. |
| 627 | def _release(self): |
| 628 | try: |
| 629 | if self._action: |
| 630 | self._action() |
| 631 | # enter draining state |
| 632 | self._state = 1 |
| 633 | self._cond.notify_all() |
| 634 | except: |
| 635 | #an exception during the _action handler. Break and reraise |
| 636 | self._break() |
| 637 | raise |
| 638 | |
| 639 | # Wait in the barrier until we are relased. Raise an exception |
| 640 | # if the barrier is reset or broken. |
| 641 | def _wait(self, timeout): |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 642 | if not self._cond.wait_for(lambda : self._state != 0, timeout): |
| 643 | #timed out. Break the barrier |
| 644 | self._break() |
| 645 | raise BrokenBarrierError |
| 646 | if self._state < 0: |
| 647 | raise BrokenBarrierError |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 648 | assert self._state == 1 |
| 649 | |
| 650 | # If we are the last thread to exit the barrier, signal any threads |
| 651 | # waiting for the barrier to drain. |
| 652 | def _exit(self): |
| 653 | if self._count == 0: |
| 654 | if self._state in (-1, 1): |
| 655 | #resetting or draining |
| 656 | self._state = 0 |
| 657 | self._cond.notify_all() |
| 658 | |
| 659 | def reset(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 660 | """Reset the barrier to the initial state. |
| 661 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 662 | Any threads currently waiting will get the BrokenBarrier exception |
| 663 | raised. |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 664 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 665 | """ |
| 666 | with self._cond: |
| 667 | if self._count > 0: |
| 668 | if self._state == 0: |
| 669 | #reset the barrier, waking up threads |
| 670 | self._state = -1 |
| 671 | elif self._state == -2: |
| 672 | #was broken, set it to reset state |
| 673 | #which clears when the last thread exits |
| 674 | self._state = -1 |
| 675 | else: |
| 676 | self._state = 0 |
| 677 | self._cond.notify_all() |
| 678 | |
| 679 | def abort(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 680 | """Place the barrier into a 'broken' state. |
| 681 | |
| 682 | Useful in case of error. Any currently waiting threads and threads |
| 683 | attempting to 'wait()' will have BrokenBarrierError raised. |
| 684 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 685 | """ |
| 686 | with self._cond: |
| 687 | self._break() |
| 688 | |
| 689 | def _break(self): |
| 690 | # An internal error was detected. The barrier is set to |
| 691 | # a broken state all parties awakened. |
| 692 | self._state = -2 |
| 693 | self._cond.notify_all() |
| 694 | |
| 695 | @property |
| 696 | def parties(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 697 | """Return the number of threads required to trip the barrier.""" |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 698 | return self._parties |
| 699 | |
| 700 | @property |
| 701 | def n_waiting(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 702 | """Return the number of threads currently waiting at the barrier.""" |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 703 | # We don't need synchronization here since this is an ephemeral result |
| 704 | # anyway. It returns the correct value in the steady state. |
| 705 | if self._state == 0: |
| 706 | return self._count |
| 707 | return 0 |
| 708 | |
| 709 | @property |
| 710 | def broken(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 711 | """Return True if the barrier is in a broken state.""" |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 712 | return self._state == -2 |
| 713 | |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 714 | # exception raised by the Barrier class |
| 715 | class BrokenBarrierError(RuntimeError): |
| 716 | pass |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 717 | |
| 718 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 719 | # Helper to generate new thread names |
R David Murray | b186f1df | 2014-10-04 17:43:54 -0400 | [diff] [blame] | 720 | _counter = _count().__next__ |
| 721 | _counter() # Consume 0 so first non-main thread has id 1. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 722 | def _newname(template="Thread-%d"): |
R David Murray | b186f1df | 2014-10-04 17:43:54 -0400 | [diff] [blame] | 723 | return template % _counter() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 724 | |
| 725 | # Active thread administration |
| 726 | _active_limbo_lock = _allocate_lock() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 727 | _active = {} # maps thread id to Thread object |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 728 | _limbo = {} |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 729 | _dangling = WeakSet() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 730 | |
| 731 | # Main class for threads |
| 732 | |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 733 | class Thread: |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 734 | """A class that represents a thread of control. |
| 735 | |
| 736 | This class can be safely subclassed in a limited fashion. There are two ways |
| 737 | to specify the activity: by passing a callable object to the constructor, or |
| 738 | by overriding the run() method in a subclass. |
| 739 | |
| 740 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 741 | |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 742 | _initialized = False |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 743 | # Need to store a reference to sys.exc_info for printing |
| 744 | # out exceptions when a thread tries to use a global var. during interp. |
| 745 | # shutdown and thus raises an exception about trying to perform some |
| 746 | # operation on/with a NoneType |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 747 | _exc_info = _sys.exc_info |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 748 | # Keep sys.exc_clear too to clear the exception just before |
| 749 | # allowing .join() to return. |
| 750 | #XXX __exc_clear = _sys.exc_clear |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 751 | |
| 752 | def __init__(self, group=None, target=None, name=None, |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 753 | args=(), kwargs=None, *, daemon=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 754 | """This constructor should always be called with keyword arguments. Arguments are: |
| 755 | |
| 756 | *group* should be None; reserved for future extension when a ThreadGroup |
| 757 | class is implemented. |
| 758 | |
| 759 | *target* is the callable object to be invoked by the run() |
| 760 | method. Defaults to None, meaning nothing is called. |
| 761 | |
| 762 | *name* is the thread name. By default, a unique name is constructed of |
| 763 | the form "Thread-N" where N is a small decimal number. |
| 764 | |
| 765 | *args* is the argument tuple for the target invocation. Defaults to (). |
| 766 | |
| 767 | *kwargs* is a dictionary of keyword arguments for the target |
| 768 | invocation. Defaults to {}. |
| 769 | |
| 770 | If a subclass overrides the constructor, it must make sure to invoke |
| 771 | the base class constructor (Thread.__init__()) before doing anything |
| 772 | else to the thread. |
| 773 | |
| 774 | """ |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 775 | assert group is None, "group argument must be None for now" |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 776 | if kwargs is None: |
| 777 | kwargs = {} |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 778 | self._target = target |
| 779 | self._name = str(name or _newname()) |
| 780 | self._args = args |
| 781 | self._kwargs = kwargs |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 782 | if daemon is not None: |
| 783 | self._daemonic = daemon |
| 784 | else: |
| 785 | self._daemonic = current_thread().daemon |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 786 | self._ident = None |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 787 | self._tstate_lock = None |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 788 | self._started = Event() |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 789 | self._is_stopped = False |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 790 | self._initialized = True |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 791 | # sys.stderr is not stored in the class like |
| 792 | # sys.exc_info since it can be changed between instances |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 793 | self._stderr = _sys.stderr |
Antoine Pitrou | 5da7e79 | 2013-09-08 13:19:06 +0200 | [diff] [blame] | 794 | # For debugging and _after_fork() |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 795 | _dangling.add(self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 796 | |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 797 | def _reset_internal_locks(self, is_alive): |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 798 | # private! Called by _after_fork() to reset our internal locks as |
| 799 | # they may be in an invalid state leading to a deadlock or crash. |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 800 | self._started._reset_internal_locks() |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 801 | if is_alive: |
| 802 | self._set_tstate_lock() |
| 803 | else: |
| 804 | # The thread isn't alive after fork: it doesn't have a tstate |
| 805 | # anymore. |
Tim Peters | b5e9ac9 | 2013-09-09 14:41:50 -0500 | [diff] [blame] | 806 | self._is_stopped = True |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 807 | self._tstate_lock = None |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 808 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 809 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 810 | assert self._initialized, "Thread.__init__() was not called" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 811 | status = "initial" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 812 | if self._started.is_set(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 813 | status = "started" |
Tim Peters | 72460fa | 2013-09-09 18:48:24 -0500 | [diff] [blame] | 814 | self.is_alive() # easy way to get ._is_stopped set when appropriate |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 815 | if self._is_stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 816 | status = "stopped" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 817 | if self._daemonic: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 818 | status += " daemon" |
| 819 | if self._ident is not None: |
| 820 | status += " %s" % self._ident |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 821 | return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 822 | |
| 823 | def start(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 824 | """Start the thread's activity. |
| 825 | |
| 826 | It must be called at most once per thread object. It arranges for the |
| 827 | object's run() method to be invoked in a separate thread of control. |
| 828 | |
| 829 | This method will raise a RuntimeError if called more than once on the |
| 830 | same thread object. |
| 831 | |
| 832 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 833 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 834 | raise RuntimeError("thread.__init__() not called") |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 835 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 836 | if self._started.is_set(): |
Senthil Kumaran | fdd4d0f | 2010-04-06 03:30:18 +0000 | [diff] [blame] | 837 | raise RuntimeError("threads can only be started once") |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 838 | with _active_limbo_lock: |
| 839 | _limbo[self] = self |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 840 | try: |
| 841 | _start_new_thread(self._bootstrap, ()) |
| 842 | except Exception: |
| 843 | with _active_limbo_lock: |
| 844 | del _limbo[self] |
| 845 | raise |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 846 | self._started.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 847 | |
| 848 | def run(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 849 | """Method representing the thread's activity. |
| 850 | |
| 851 | You may override this method in a subclass. The standard run() method |
| 852 | invokes the callable object passed to the object's constructor as the |
| 853 | target argument, if any, with sequential and keyword arguments taken |
| 854 | from the args and kwargs arguments, respectively. |
| 855 | |
| 856 | """ |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 857 | try: |
| 858 | if self._target: |
| 859 | self._target(*self._args, **self._kwargs) |
| 860 | finally: |
| 861 | # Avoid a refcycle if the thread is running a function with |
| 862 | # an argument that has a member that points to the thread. |
| 863 | del self._target, self._args, self._kwargs |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 864 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 865 | def _bootstrap(self): |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 866 | # Wrapper around the real bootstrap code that ignores |
| 867 | # exceptions during interpreter cleanup. Those typically |
| 868 | # happen when a daemon thread wakes up at an unfortunate |
| 869 | # moment, finds the world around it destroyed, and raises some |
| 870 | # random exception *** while trying to report the exception in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 871 | # _bootstrap_inner() below ***. Those random exceptions |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 872 | # don't help anybody, and they confuse users, so we suppress |
| 873 | # them. We suppress them only when it appears that the world |
| 874 | # indeed has already been destroyed, so that exceptions in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 875 | # _bootstrap_inner() during normal business hours are properly |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 876 | # reported. Also, we only suppress them for daemonic threads; |
| 877 | # if a non-daemonic encounters this, something else is wrong. |
| 878 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 879 | self._bootstrap_inner() |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 880 | except: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 881 | if self._daemonic and _sys is None: |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 882 | return |
| 883 | raise |
| 884 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 885 | def _set_ident(self): |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 886 | self._ident = get_ident() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 887 | |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 888 | def _set_tstate_lock(self): |
| 889 | """ |
| 890 | Set a lock object which will be released by the interpreter when |
| 891 | the underlying thread state (see pystate.h) gets deleted. |
| 892 | """ |
| 893 | self._tstate_lock = _set_sentinel() |
| 894 | self._tstate_lock.acquire() |
| 895 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 896 | def _bootstrap_inner(self): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 897 | try: |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 898 | self._set_ident() |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 899 | self._set_tstate_lock() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 900 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 901 | with _active_limbo_lock: |
| 902 | _active[self._ident] = self |
| 903 | del _limbo[self] |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 904 | |
| 905 | if _trace_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 906 | _sys.settrace(_trace_hook) |
| 907 | if _profile_hook: |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 908 | _sys.setprofile(_profile_hook) |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 909 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 910 | try: |
| 911 | self.run() |
| 912 | except SystemExit: |
Victor Stinner | 135b6d8 | 2012-03-03 01:32:57 +0100 | [diff] [blame] | 913 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 914 | except: |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 915 | # If sys.stderr is no more (most likely from interpreter |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 916 | # shutdown) use self._stderr. Otherwise still use sys (as in |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 917 | # _sys) in case sys.stderr was redefined since the creation of |
| 918 | # self. |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 919 | if _sys and _sys.stderr is not None: |
| 920 | print("Exception in thread %s:\n%s" % |
| 921 | (self.name, _format_exc()), file=self._stderr) |
| 922 | elif self._stderr is not None: |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 923 | # Do the best job possible w/o a huge amt. of code to |
| 924 | # approximate a traceback (code ideas from |
| 925 | # Lib/traceback.py) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 926 | exc_type, exc_value, exc_tb = self._exc_info() |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 927 | try: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 928 | print(( |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 929 | "Exception in thread " + self.name + |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 930 | " (most likely raised during interpreter shutdown):"), file=self._stderr) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 931 | print(( |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 932 | "Traceback (most recent call last):"), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 933 | while exc_tb: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 934 | print(( |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 935 | ' File "%s", line %s, in %s' % |
| 936 | (exc_tb.tb_frame.f_code.co_filename, |
| 937 | exc_tb.tb_lineno, |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 938 | exc_tb.tb_frame.f_code.co_name)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 939 | exc_tb = exc_tb.tb_next |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 940 | print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 941 | # Make sure that exc_tb gets deleted since it is a memory |
| 942 | # hog; deleting everything else is just for thoroughness |
| 943 | finally: |
| 944 | del exc_type, exc_value, exc_tb |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 945 | finally: |
| 946 | # Prevent a race in |
| 947 | # test_threading.test_no_refcycle_through_target when |
| 948 | # the exception keeps the target alive past when we |
| 949 | # assert that it's dead. |
Serhiy Storchaka | 52005c2 | 2014-09-21 22:08:13 +0300 | [diff] [blame] | 950 | #XXX self._exc_clear() |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 951 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 952 | finally: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 953 | with _active_limbo_lock: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 954 | try: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 955 | # We don't call self._delete() because it also |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 956 | # grabs _active_limbo_lock. |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 957 | del _active[get_ident()] |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 958 | except: |
| 959 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 960 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 961 | def _stop(self): |
Tim Peters | b5e9ac9 | 2013-09-09 14:41:50 -0500 | [diff] [blame] | 962 | # After calling ._stop(), .is_alive() returns False and .join() returns |
| 963 | # immediately. ._tstate_lock must be released before calling ._stop(). |
| 964 | # |
| 965 | # Normal case: C code at the end of the thread's life |
| 966 | # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and |
| 967 | # that's detected by our ._wait_for_tstate_lock(), called by .join() |
| 968 | # and .is_alive(). Any number of threads _may_ call ._stop() |
| 969 | # simultaneously (for example, if multiple threads are blocked in |
| 970 | # .join() calls), and they're not serialized. That's harmless - |
| 971 | # they'll just make redundant rebindings of ._is_stopped and |
| 972 | # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the |
| 973 | # "assert self._is_stopped" in ._wait_for_tstate_lock() always works |
| 974 | # (the assert is executed only if ._tstate_lock is None). |
| 975 | # |
| 976 | # Special case: _main_thread releases ._tstate_lock via this |
| 977 | # module's _shutdown() function. |
| 978 | lock = self._tstate_lock |
| 979 | if lock is not None: |
| 980 | assert not lock.locked() |
Tim Peters | 7875523 | 2013-09-09 13:47:16 -0500 | [diff] [blame] | 981 | self._is_stopped = True |
| 982 | self._tstate_lock = None |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 983 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 984 | def _delete(self): |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 985 | "Remove current thread from the dict of currently running threads." |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 986 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 987 | # Notes about running with _dummy_thread: |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 988 | # |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 989 | # Must take care to not raise an exception if _dummy_thread is being |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 990 | # used (and thus this module is being used as an instance of |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 991 | # dummy_threading). _dummy_thread.get_ident() always returns -1 since |
| 992 | # there is only one thread if _dummy_thread is being used. Thus |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 993 | # len(_active) is always <= 1 here, and any Thread instance created |
| 994 | # overwrites the (if any) thread currently registered in _active. |
| 995 | # |
| 996 | # An instance of _MainThread is always created by 'threading'. This |
| 997 | # gets overwritten the instant an instance of Thread is created; both |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 998 | # threads return -1 from _dummy_thread.get_ident() and thus have the |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 999 | # same key in the dict. So when the _MainThread instance created by |
| 1000 | # 'threading' tries to clean itself up when atexit calls this method |
| 1001 | # it gets a KeyError if another Thread instance was created. |
| 1002 | # |
| 1003 | # This all means that KeyError from trying to delete something from |
| 1004 | # _active if dummy_threading is being used is a red herring. But |
| 1005 | # since it isn't if dummy_threading is *not* being used then don't |
| 1006 | # hide the exception. |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 1007 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 1008 | try: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 1009 | with _active_limbo_lock: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 1010 | del _active[get_ident()] |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 1011 | # There must not be any python code between the previous line |
| 1012 | # and after the lock is released. Otherwise a tracing function |
| 1013 | # could try to acquire the lock again in the same thread, (in |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1014 | # current_thread()), and would block. |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 1015 | except KeyError: |
| 1016 | if 'dummy_threading' not in _sys.modules: |
| 1017 | raise |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1018 | |
| 1019 | def join(self, timeout=None): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1020 | """Wait until the thread terminates. |
| 1021 | |
| 1022 | This blocks the calling thread until the thread whose join() method is |
| 1023 | called terminates -- either normally or through an unhandled exception |
| 1024 | or until the optional timeout occurs. |
| 1025 | |
| 1026 | When the timeout argument is present and not None, it should be a |
| 1027 | floating point number specifying a timeout for the operation in seconds |
| 1028 | (or fractions thereof). As join() always returns None, you must call |
| 1029 | isAlive() after join() to decide whether a timeout happened -- if the |
| 1030 | thread is still alive, the join() call timed out. |
| 1031 | |
| 1032 | When the timeout argument is not present or None, the operation will |
| 1033 | block until the thread terminates. |
| 1034 | |
| 1035 | A thread can be join()ed many times. |
| 1036 | |
| 1037 | join() raises a RuntimeError if an attempt is made to join the current |
| 1038 | thread as that would cause a deadlock. It is also an error to join() a |
| 1039 | thread before it has been started and attempts to do so raises the same |
| 1040 | exception. |
| 1041 | |
| 1042 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1043 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1044 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1045 | if not self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1046 | raise RuntimeError("cannot join thread before it is started") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1047 | if self is current_thread(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1048 | raise RuntimeError("cannot join current thread") |
Tim Peters | e5bb0bf | 2013-10-25 20:46:51 -0500 | [diff] [blame] | 1049 | |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1050 | if timeout is None: |
| 1051 | self._wait_for_tstate_lock() |
Tim Peters | 7bad39f | 2013-10-25 22:33:52 -0500 | [diff] [blame] | 1052 | else: |
| 1053 | # the behavior of a negative timeout isn't documented, but |
Tim Peters | a577f1e | 2013-10-26 11:56:16 -0500 | [diff] [blame] | 1054 | # historically .join(timeout=x) for x<0 has acted as if timeout=0 |
Tim Peters | 7bad39f | 2013-10-25 22:33:52 -0500 | [diff] [blame] | 1055 | self._wait_for_tstate_lock(timeout=max(timeout, 0)) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1056 | |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1057 | def _wait_for_tstate_lock(self, block=True, timeout=-1): |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1058 | # Issue #18808: wait for the thread state to be gone. |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1059 | # At the end of the thread's life, after all knowledge of the thread |
| 1060 | # is removed from C data structures, C code releases our _tstate_lock. |
| 1061 | # This method passes its arguments to _tstate_lock.aquire(). |
| 1062 | # If the lock is acquired, the C code is done, and self._stop() is |
| 1063 | # called. That sets ._is_stopped to True, and ._tstate_lock to None. |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1064 | lock = self._tstate_lock |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1065 | if lock is None: # already determined that the C code is done |
| 1066 | assert self._is_stopped |
| 1067 | elif lock.acquire(block, timeout): |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1068 | lock.release() |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1069 | self._stop() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1070 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1071 | @property |
| 1072 | def name(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1073 | """A string used for identification purposes only. |
| 1074 | |
| 1075 | It has no semantics. Multiple threads may be given the same name. The |
| 1076 | initial name is set by the constructor. |
| 1077 | |
| 1078 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1079 | assert self._initialized, "Thread.__init__() not called" |
| 1080 | return self._name |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1081 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1082 | @name.setter |
| 1083 | def name(self, name): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1084 | assert self._initialized, "Thread.__init__() not called" |
| 1085 | self._name = str(name) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1086 | |
Benjamin Peterson | 773c17b | 2008-08-18 16:45:31 +0000 | [diff] [blame] | 1087 | @property |
| 1088 | def ident(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1089 | """Thread identifier of this thread or None if it has not been started. |
| 1090 | |
| 1091 | This is a nonzero integer. See the thread.get_ident() function. Thread |
| 1092 | identifiers may be recycled when a thread exits and another thread is |
| 1093 | created. The identifier is available even after the thread has exited. |
| 1094 | |
| 1095 | """ |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1096 | assert self._initialized, "Thread.__init__() not called" |
| 1097 | return self._ident |
| 1098 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1099 | def is_alive(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1100 | """Return whether the thread is alive. |
| 1101 | |
| 1102 | This method returns True just before the run() method starts until just |
| 1103 | after the run() method terminates. The module function enumerate() |
| 1104 | returns a list of all alive threads. |
| 1105 | |
| 1106 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1107 | assert self._initialized, "Thread.__init__() not called" |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1108 | if self._is_stopped or not self._started.is_set(): |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1109 | return False |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1110 | self._wait_for_tstate_lock(False) |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1111 | return not self._is_stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 1112 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1113 | isAlive = is_alive |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1114 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1115 | @property |
| 1116 | def daemon(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1117 | """A boolean value indicating whether this thread is a daemon thread. |
| 1118 | |
| 1119 | This must be set before start() is called, otherwise RuntimeError is |
| 1120 | raised. Its initial value is inherited from the creating thread; the |
| 1121 | main thread is not a daemon thread and therefore all threads created in |
| 1122 | the main thread default to daemon = False. |
| 1123 | |
| 1124 | The entire Python program exits when no alive non-daemon threads are |
| 1125 | left. |
| 1126 | |
| 1127 | """ |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1128 | assert self._initialized, "Thread.__init__() not called" |
| 1129 | return self._daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1130 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 1131 | @daemon.setter |
| 1132 | def daemon(self, daemonic): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1133 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 1134 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1135 | if self._started.is_set(): |
Antoine Pitrou | 1095907 | 2014-03-17 18:22:41 +0100 | [diff] [blame] | 1136 | raise RuntimeError("cannot set daemon status of active thread") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1137 | self._daemonic = daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1138 | |
Benjamin Peterson | 6640d72 | 2008-08-18 18:16:46 +0000 | [diff] [blame] | 1139 | def isDaemon(self): |
| 1140 | return self.daemon |
| 1141 | |
| 1142 | def setDaemon(self, daemonic): |
| 1143 | self.daemon = daemonic |
| 1144 | |
| 1145 | def getName(self): |
| 1146 | return self.name |
| 1147 | |
| 1148 | def setName(self, name): |
| 1149 | self.name = name |
| 1150 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1151 | # The timer class was contributed by Itamar Shtull-Trauring |
| 1152 | |
Éric Araujo | 0cdd445 | 2011-07-28 00:28:28 +0200 | [diff] [blame] | 1153 | class Timer(Thread): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1154 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1155 | |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1156 | t = Timer(30.0, f, args=None, kwargs=None) |
| 1157 | t.start() |
| 1158 | t.cancel() # stop the timer's action if it's still waiting |
| 1159 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1160 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1161 | |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 1162 | def __init__(self, interval, function, args=None, kwargs=None): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1163 | Thread.__init__(self) |
| 1164 | self.interval = interval |
| 1165 | self.function = function |
R David Murray | 19aeb43 | 2013-03-30 17:19:38 -0400 | [diff] [blame] | 1166 | self.args = args if args is not None else [] |
| 1167 | self.kwargs = kwargs if kwargs is not None else {} |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1168 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1169 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1170 | def cancel(self): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1171 | """Stop the timer if it hasn't finished yet.""" |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1172 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 1173 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1174 | def run(self): |
| 1175 | self.finished.wait(self.interval) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1176 | if not self.finished.is_set(): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 1177 | self.function(*self.args, **self.kwargs) |
| 1178 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1179 | |
| 1180 | # Special thread class to represent the main thread |
| 1181 | # This is garbage collected through an exit handler |
| 1182 | |
| 1183 | class _MainThread(Thread): |
| 1184 | |
| 1185 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 1186 | Thread.__init__(self, name="MainThread", daemon=False) |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1187 | self._set_tstate_lock() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 1188 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1189 | self._set_ident() |
| 1190 | with _active_limbo_lock: |
| 1191 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1192 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1193 | |
| 1194 | # Dummy thread class to represent threads not started here. |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1195 | # These aren't garbage collected when they die, nor can they be waited for. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1196 | # If they invoke anything in threading.py that calls current_thread(), they |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1197 | # leave an entry in the _active dict forever after. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1198 | # Their purpose is to return *something* from current_thread(). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1199 | # They are marked as daemon threads so we won't wait for them |
| 1200 | # when we exit (conform previous semantics). |
| 1201 | |
| 1202 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 1203 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1204 | def __init__(self): |
Antoine Pitrou | 0bd4deb | 2011-02-25 22:07:43 +0000 | [diff] [blame] | 1205 | Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1206 | |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 1207 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1208 | self._set_ident() |
| 1209 | with _active_limbo_lock: |
| 1210 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1211 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 1212 | def _stop(self): |
| 1213 | pass |
| 1214 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 1215 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 1216 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1217 | |
| 1218 | |
| 1219 | # Global API functions |
| 1220 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1221 | def current_thread(): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1222 | """Return the current Thread object, corresponding to the caller's thread of control. |
| 1223 | |
| 1224 | If the caller's thread of control was not created through the threading |
| 1225 | module, a dummy thread object with limited functionality is returned. |
| 1226 | |
| 1227 | """ |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1228 | try: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 1229 | return _active[get_ident()] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1230 | except KeyError: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1231 | return _DummyThread() |
| 1232 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1233 | currentThread = current_thread |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1234 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1235 | def active_count(): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1236 | """Return the number of Thread objects currently alive. |
| 1237 | |
| 1238 | The returned count is equal to the length of the list returned by |
| 1239 | enumerate(). |
| 1240 | |
| 1241 | """ |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1242 | with _active_limbo_lock: |
| 1243 | return len(_active) + len(_limbo) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1244 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1245 | activeCount = active_count |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1246 | |
Antoine Pitrou | bdec11f | 2009-11-05 13:49:14 +0000 | [diff] [blame] | 1247 | def _enumerate(): |
| 1248 | # Same as enumerate(), but without the lock. Internal use only. |
| 1249 | return list(_active.values()) + list(_limbo.values()) |
| 1250 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1251 | def enumerate(): |
Georg Brandl | c30b59f | 2013-10-13 10:43:59 +0200 | [diff] [blame] | 1252 | """Return a list of all Thread objects currently alive. |
| 1253 | |
| 1254 | The list includes daemonic threads, dummy thread objects created by |
| 1255 | current_thread(), and the main thread. It excludes terminated threads and |
| 1256 | threads that have not yet been started. |
| 1257 | |
| 1258 | """ |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1259 | with _active_limbo_lock: |
| 1260 | return list(_active.values()) + list(_limbo.values()) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1261 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 1262 | from _thread import stack_size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1263 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1264 | # Create the main thread object, |
| 1265 | # and make it available for the interpreter |
| 1266 | # (Py_Main) as threading._shutdown. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1267 | |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1268 | _main_thread = _MainThread() |
| 1269 | |
| 1270 | def _shutdown(): |
Tim Peters | c363a23 | 2013-09-08 18:44:40 -0500 | [diff] [blame] | 1271 | # Obscure: other threads may be waiting to join _main_thread. That's |
| 1272 | # dubious, but some code does it. We can't wait for C code to release |
| 1273 | # the main thread's tstate_lock - that won't happen until the interpreter |
| 1274 | # is nearly dead. So we release it here. Note that just calling _stop() |
| 1275 | # isn't enough: other threads may already be waiting on _tstate_lock. |
Tim Peters | b5e9ac9 | 2013-09-09 14:41:50 -0500 | [diff] [blame] | 1276 | tlock = _main_thread._tstate_lock |
| 1277 | # The main thread isn't finished yet, so its thread state lock can't have |
| 1278 | # been released. |
| 1279 | assert tlock is not None |
| 1280 | assert tlock.locked() |
| 1281 | tlock.release() |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1282 | _main_thread._stop() |
| 1283 | t = _pickSomeNonDaemonThread() |
| 1284 | while t: |
| 1285 | t.join() |
| 1286 | t = _pickSomeNonDaemonThread() |
| 1287 | _main_thread._delete() |
| 1288 | |
| 1289 | def _pickSomeNonDaemonThread(): |
| 1290 | for t in enumerate(): |
| 1291 | if not t.daemon and t.is_alive(): |
| 1292 | return t |
| 1293 | return None |
| 1294 | |
| 1295 | def main_thread(): |
Andrew Svetlov | b1dd557 | 2013-09-04 10:33:11 +0300 | [diff] [blame] | 1296 | """Return the main thread object. |
| 1297 | |
| 1298 | In normal conditions, the main thread is the thread from which the |
| 1299 | Python interpreter was started. |
| 1300 | """ |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1301 | return _main_thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1302 | |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 1303 | # get thread-local implementation, either from the thread |
| 1304 | # module, or from the python fallback |
| 1305 | |
| 1306 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 1307 | from _thread import _local as local |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 1308 | except ImportError: |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 1309 | from _threading_local import local |
| 1310 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1311 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1312 | def _after_fork(): |
| 1313 | # This function is called by Python/ceval.c:PyEval_ReInitThreads which |
| 1314 | # is called from PyOS_AfterFork. Here we cleanup threading module state |
| 1315 | # that should not exist after a fork. |
| 1316 | |
| 1317 | # Reset _active_limbo_lock, in case we forked while the lock was held |
| 1318 | # by another (non-forked) thread. http://bugs.python.org/issue874900 |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1319 | global _active_limbo_lock, _main_thread |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1320 | _active_limbo_lock = _allocate_lock() |
| 1321 | |
| 1322 | # fork() only copied the current thread; clear references to others. |
| 1323 | new_active = {} |
| 1324 | current = current_thread() |
Andrew Svetlov | 58b5c5a | 2013-09-04 07:01:07 +0300 | [diff] [blame] | 1325 | _main_thread = current |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1326 | with _active_limbo_lock: |
Antoine Pitrou | 5da7e79 | 2013-09-08 13:19:06 +0200 | [diff] [blame] | 1327 | # Dangling thread instances must still have their locks reset, |
| 1328 | # because someone may join() them. |
| 1329 | threads = set(_enumerate()) |
| 1330 | threads.update(_dangling) |
| 1331 | for thread in threads: |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 1332 | # Any lock/condition variable may be currently locked or in an |
| 1333 | # invalid state, so we reinitialize them. |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1334 | if thread is current: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 1335 | # There is only one active thread. We reset the ident to |
| 1336 | # its new value since it can have changed. |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1337 | thread._reset_internal_locks(True) |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 1338 | ident = get_ident() |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 1339 | thread._ident = ident |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1340 | new_active[ident] = thread |
| 1341 | else: |
| 1342 | # All the others are already stopped. |
Antoine Pitrou | 7b47699 | 2013-09-07 23:38:37 +0200 | [diff] [blame] | 1343 | thread._reset_internal_locks(False) |
Charles-François Natali | b055bf6 | 2011-12-18 18:45:16 +0100 | [diff] [blame] | 1344 | thread._stop() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1345 | |
| 1346 | _limbo.clear() |
| 1347 | _active.clear() |
| 1348 | _active.update(new_active) |
| 1349 | assert len(_active) == 1 |