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