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