Jeremy Hylton | 92bb6e7 | 2002-08-14 19:25:42 +0000 | [diff] [blame] | 1 | """Thread module emulating a subset of Java's threading model.""" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 2 | |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 3 | import sys as _sys |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 4 | import _thread |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 5 | |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 6 | from time import time as _time, sleep as _sleep |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 7 | from traceback import format_exc as _format_exc |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 8 | from _weakrefset import WeakSet |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 9 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 10 | # Note regarding PEP 8 compliant names |
| 11 | # This threading model was originally inspired by Java, and inherited |
| 12 | # the convention of camelCase function and method names from that |
| 13 | # language. Those originaly names are not in any imminent danger of |
| 14 | # being deprecated (even for Py3k),so this module provides them as an |
| 15 | # alias for the PEP 8 compliant names |
| 16 | # Note that using the new PEP 8 compliant names facilitates substitution |
| 17 | # with the multiprocessing module, which doesn't provide the old |
| 18 | # Java inspired names. |
| 19 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 20 | __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event', |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 21 | 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 22 | 'Timer', 'setprofile', 'settrace', 'local', 'stack_size'] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 23 | |
Raymond Hettinger | 5cee47f | 2011-01-11 19:59:46 +0000 | [diff] [blame] | 24 | # Rename some stuff so "from threading import *" is safe |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 25 | _start_new_thread = _thread.start_new_thread |
| 26 | _allocate_lock = _thread.allocate_lock |
| 27 | _get_ident = _thread.get_ident |
| 28 | ThreadError = _thread.error |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 29 | try: |
| 30 | _CRLock = _thread.RLock |
| 31 | except AttributeError: |
| 32 | _CRLock = None |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 33 | TIMEOUT_MAX = _thread.TIMEOUT_MAX |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 34 | del _thread |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 35 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 36 | |
Tim Peters | 59aba12 | 2003-07-01 20:01:55 +0000 | [diff] [blame] | 37 | # Debug support (adapted from ihooks.py). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 38 | |
Tim Peters | 0939fac | 2003-07-01 19:28:44 +0000 | [diff] [blame] | 39 | _VERBOSE = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 40 | |
| 41 | if __debug__: |
| 42 | |
Tim Peters | 59aba12 | 2003-07-01 20:01:55 +0000 | [diff] [blame] | 43 | class _Verbose(object): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 44 | |
| 45 | def __init__(self, verbose=None): |
| 46 | if verbose is None: |
| 47 | verbose = _VERBOSE |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 48 | self._verbose = verbose |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 49 | |
| 50 | def _note(self, format, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 51 | if self._verbose: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 52 | format = format % args |
Antoine Pitrou | 401edd6 | 2010-12-17 17:42:16 +0000 | [diff] [blame] | 53 | # Issue #4188: calling current_thread() can incur an infinite |
| 54 | # recursion if it has to create a DummyThread on the fly. |
| 55 | ident = _get_ident() |
| 56 | try: |
| 57 | name = _active[ident].name |
| 58 | except KeyError: |
| 59 | name = "<OS thread %d>" % ident |
| 60 | format = "%s: %s\n" % (name, format) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 61 | _sys.stderr.write(format) |
| 62 | |
| 63 | else: |
| 64 | # Disable this when using "python -O" |
Tim Peters | 59aba12 | 2003-07-01 20:01:55 +0000 | [diff] [blame] | 65 | class _Verbose(object): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 66 | def __init__(self, verbose=None): |
| 67 | pass |
| 68 | def _note(self, *args): |
| 69 | pass |
| 70 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 71 | # Support for profile and trace hooks |
| 72 | |
| 73 | _profile_hook = None |
| 74 | _trace_hook = None |
| 75 | |
| 76 | def setprofile(func): |
| 77 | global _profile_hook |
| 78 | _profile_hook = func |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 79 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 80 | def settrace(func): |
| 81 | global _trace_hook |
| 82 | _trace_hook = func |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 83 | |
| 84 | # Synchronization classes |
| 85 | |
| 86 | Lock = _allocate_lock |
| 87 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 88 | def RLock(verbose=None, *args, **kwargs): |
| 89 | if verbose is None: |
| 90 | verbose = _VERBOSE |
| 91 | if (__debug__ and verbose) or _CRLock is None: |
| 92 | return _PyRLock(verbose, *args, **kwargs) |
| 93 | return _CRLock(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 94 | |
| 95 | class _RLock(_Verbose): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 96 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 97 | def __init__(self, verbose=None): |
| 98 | _Verbose.__init__(self, verbose) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 99 | self._block = _allocate_lock() |
| 100 | self._owner = None |
| 101 | self._count = 0 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 102 | |
| 103 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 104 | owner = self._owner |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 105 | try: |
| 106 | owner = _active[owner].name |
| 107 | except KeyError: |
| 108 | pass |
| 109 | return "<%s owner=%r count=%d>" % ( |
| 110 | self.__class__.__name__, owner, self._count) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 111 | |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 112 | def acquire(self, blocking=True, timeout=-1): |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 113 | me = _get_ident() |
| 114 | if self._owner == me: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 115 | self._count = self._count + 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 116 | if __debug__: |
| 117 | self._note("%s.acquire(%s): recursive success", self, blocking) |
| 118 | return 1 |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 119 | rc = self._block.acquire(blocking, timeout) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 120 | if rc: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 121 | self._owner = me |
| 122 | self._count = 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 123 | if __debug__: |
Brett Cannon | 90cece7 | 2005-01-27 22:48:30 +0000 | [diff] [blame] | 124 | self._note("%s.acquire(%s): initial success", self, blocking) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 125 | else: |
| 126 | if __debug__: |
| 127 | self._note("%s.acquire(%s): failure", self, blocking) |
| 128 | return rc |
| 129 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 130 | __enter__ = acquire |
| 131 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 132 | def release(self): |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 133 | if self._owner != _get_ident(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 134 | raise RuntimeError("cannot release un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 135 | self._count = count = self._count - 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 136 | if not count: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 137 | self._owner = None |
| 138 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 139 | if __debug__: |
| 140 | self._note("%s.release(): final release", self) |
| 141 | else: |
| 142 | if __debug__: |
| 143 | self._note("%s.release(): non-final release", self) |
| 144 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 145 | def __exit__(self, t, v, tb): |
| 146 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 147 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 148 | # Internal methods used by condition variables |
| 149 | |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 150 | def _acquire_restore(self, state): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 151 | self._block.acquire() |
| 152 | self._count, self._owner = state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 153 | if __debug__: |
| 154 | self._note("%s._acquire_restore()", self) |
| 155 | |
| 156 | def _release_save(self): |
| 157 | if __debug__: |
| 158 | self._note("%s._release_save()", self) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 159 | count = self._count |
| 160 | self._count = 0 |
| 161 | owner = self._owner |
| 162 | self._owner = None |
| 163 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 164 | return (count, owner) |
| 165 | |
| 166 | def _is_owned(self): |
Antoine Pitrou | b087268 | 2009-11-09 16:08:16 +0000 | [diff] [blame] | 167 | return self._owner == _get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 168 | |
Antoine Pitrou | 434736a | 2009-11-10 18:46:01 +0000 | [diff] [blame] | 169 | _PyRLock = _RLock |
| 170 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 171 | |
| 172 | def Condition(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 173 | return _Condition(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 174 | |
| 175 | class _Condition(_Verbose): |
| 176 | |
| 177 | def __init__(self, lock=None, verbose=None): |
| 178 | _Verbose.__init__(self, verbose) |
| 179 | if lock is None: |
| 180 | lock = RLock() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 181 | self._lock = lock |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 182 | # Export the lock's acquire() and release() methods |
| 183 | self.acquire = lock.acquire |
| 184 | self.release = lock.release |
| 185 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 186 | # these override the default implementations (which just call |
| 187 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 188 | try: |
| 189 | self._release_save = lock._release_save |
| 190 | except AttributeError: |
| 191 | pass |
| 192 | try: |
| 193 | self._acquire_restore = lock._acquire_restore |
| 194 | except AttributeError: |
| 195 | pass |
| 196 | try: |
| 197 | self._is_owned = lock._is_owned |
| 198 | except AttributeError: |
| 199 | pass |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 200 | self._waiters = [] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 201 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 202 | def __enter__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 203 | return self._lock.__enter__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 204 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 205 | def __exit__(self, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 206 | return self._lock.__exit__(*args) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 207 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 208 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 209 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 210 | |
| 211 | def _release_save(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 212 | self._lock.release() # No state to save |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 213 | |
| 214 | def _acquire_restore(self, x): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 215 | self._lock.acquire() # Ignore saved state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 216 | |
| 217 | def _is_owned(self): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 218 | # Return True if lock is owned by current_thread. |
Jeremy Hylton | af7fde7 | 2002-08-14 17:43:59 +0000 | [diff] [blame] | 219 | # 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] | 220 | if self._lock.acquire(0): |
| 221 | self._lock.release() |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 222 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 223 | else: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 224 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 225 | |
| 226 | def wait(self, timeout=None): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 227 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 228 | raise RuntimeError("cannot wait on un-acquired lock") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 229 | waiter = _allocate_lock() |
| 230 | waiter.acquire() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 231 | self._waiters.append(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 232 | saved_state = self._release_save() |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 233 | try: # restore state no matter what (e.g., KeyboardInterrupt) |
| 234 | if timeout is None: |
| 235 | waiter.acquire() |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 236 | gotit = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 237 | if __debug__: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 238 | self._note("%s.wait(): got it", self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 239 | else: |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 240 | if timeout > 0: |
| 241 | gotit = waiter.acquire(True, timeout) |
| 242 | else: |
| 243 | gotit = waiter.acquire(False) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 244 | if not gotit: |
| 245 | if __debug__: |
| 246 | self._note("%s.wait(%s): timed out", self, timeout) |
| 247 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 248 | self._waiters.remove(waiter) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 249 | except ValueError: |
| 250 | pass |
| 251 | else: |
| 252 | if __debug__: |
| 253 | self._note("%s.wait(%s): got it", self, timeout) |
Georg Brandl | b9a4391 | 2010-10-28 09:03:20 +0000 | [diff] [blame] | 254 | return gotit |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 255 | finally: |
| 256 | self._acquire_restore(saved_state) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 257 | |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 258 | def wait_for(self, predicate, timeout=None): |
| 259 | endtime = None |
| 260 | waittime = timeout |
| 261 | result = predicate() |
| 262 | while not result: |
| 263 | if waittime is not None: |
| 264 | if endtime is None: |
| 265 | endtime = _time() + waittime |
| 266 | else: |
| 267 | waittime = endtime - _time() |
| 268 | if waittime <= 0: |
| 269 | if __debug__: |
| 270 | self._note("%s.wait_for(%r, %r): Timed out.", |
| 271 | self, predicate, timeout) |
| 272 | break |
| 273 | if __debug__: |
| 274 | self._note("%s.wait_for(%r, %r): Waiting with timeout=%s.", |
| 275 | self, predicate, timeout, waittime) |
| 276 | self.wait(waittime) |
| 277 | result = predicate() |
| 278 | else: |
| 279 | if __debug__: |
| 280 | self._note("%s.wait_for(%r, %r): Success.", |
| 281 | self, predicate, timeout) |
| 282 | return result |
| 283 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 284 | def notify(self, n=1): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 285 | if not self._is_owned(): |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 286 | raise RuntimeError("cannot notify on un-acquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 287 | __waiters = self._waiters |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 288 | waiters = __waiters[:n] |
| 289 | if not waiters: |
| 290 | if __debug__: |
| 291 | self._note("%s.notify(): no waiters", self) |
| 292 | return |
| 293 | self._note("%s.notify(): notifying %d waiter%s", self, n, |
| 294 | n!=1 and "s" or "") |
| 295 | for waiter in waiters: |
| 296 | waiter.release() |
| 297 | try: |
| 298 | __waiters.remove(waiter) |
| 299 | except ValueError: |
| 300 | pass |
| 301 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 302 | def notify_all(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 303 | self.notify(len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 304 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 305 | notifyAll = notify_all |
| 306 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 307 | |
| 308 | def Semaphore(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 309 | return _Semaphore(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 310 | |
| 311 | class _Semaphore(_Verbose): |
| 312 | |
Andrew M. Kuchling | 39d3bfc | 2000-02-29 00:10:24 +0000 | [diff] [blame] | 313 | # 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] | 314 | |
| 315 | def __init__(self, value=1, verbose=None): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 316 | if value < 0: |
| 317 | raise ValueError("semaphore initial value must be >= 0") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 318 | _Verbose.__init__(self, verbose) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 319 | self._cond = Condition(Lock()) |
| 320 | self._value = value |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 321 | |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 322 | def acquire(self, blocking=True, timeout=None): |
| 323 | if not blocking and timeout is not None: |
| 324 | raise ValueError("can't specify timeout for non-blocking acquire") |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 325 | rc = False |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 326 | endtime = None |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 327 | self._cond.acquire() |
| 328 | while self._value == 0: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 329 | if not blocking: |
| 330 | break |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 331 | if __debug__: |
| 332 | self._note("%s.acquire(%s): blocked waiting, value=%s", |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 333 | self, blocking, self._value) |
Antoine Pitrou | 0454af9 | 2010-04-17 23:51:58 +0000 | [diff] [blame] | 334 | if timeout is not None: |
| 335 | if endtime is None: |
| 336 | endtime = _time() + timeout |
| 337 | else: |
| 338 | timeout = endtime - _time() |
| 339 | if timeout <= 0: |
| 340 | break |
| 341 | self._cond.wait(timeout) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 342 | else: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 343 | self._value = self._value - 1 |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 344 | if __debug__: |
Skip Montanaro | ae8454a | 2001-08-19 05:53:47 +0000 | [diff] [blame] | 345 | self._note("%s.acquire: success, value=%s", |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 346 | self, self._value) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 347 | rc = True |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 348 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 349 | return rc |
| 350 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 351 | __enter__ = acquire |
| 352 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 353 | def release(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 354 | self._cond.acquire() |
| 355 | self._value = self._value + 1 |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 356 | if __debug__: |
Skip Montanaro | ae8454a | 2001-08-19 05:53:47 +0000 | [diff] [blame] | 357 | self._note("%s.release: success, value=%s", |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 358 | self, self._value) |
| 359 | self._cond.notify() |
| 360 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 361 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 362 | def __exit__(self, t, v, tb): |
| 363 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 364 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 365 | |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 366 | def BoundedSemaphore(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 367 | return _BoundedSemaphore(*args, **kwargs) |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 368 | |
| 369 | class _BoundedSemaphore(_Semaphore): |
| 370 | """Semaphore that checks that # releases is <= # acquires""" |
| 371 | def __init__(self, value=1, verbose=None): |
| 372 | _Semaphore.__init__(self, value, verbose) |
| 373 | self._initial_value = value |
| 374 | |
| 375 | def release(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 376 | if self._value >= self._initial_value: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 377 | raise ValueError("Semaphore released too many times") |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 378 | return _Semaphore.release(self) |
| 379 | |
| 380 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 381 | def Event(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 382 | return _Event(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 383 | |
| 384 | class _Event(_Verbose): |
| 385 | |
| 386 | # After Tim Peters' event class (without is_posted()) |
| 387 | |
| 388 | def __init__(self, verbose=None): |
| 389 | _Verbose.__init__(self, verbose) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 390 | self._cond = Condition(Lock()) |
| 391 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 392 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 393 | def _reset_internal_locks(self): |
| 394 | # private! called by Thread._reset_internal_locks by _after_fork() |
| 395 | self._cond.__init__() |
| 396 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 397 | def is_set(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 398 | return self._flag |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 399 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 400 | isSet = is_set |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 401 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 402 | def set(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 403 | self._cond.acquire() |
| 404 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 405 | self._flag = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 406 | self._cond.notify_all() |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 407 | finally: |
| 408 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 409 | |
| 410 | def clear(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 411 | self._cond.acquire() |
| 412 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 413 | self._flag = False |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 414 | finally: |
| 415 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 416 | |
| 417 | def wait(self, timeout=None): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 418 | self._cond.acquire() |
| 419 | try: |
Charles-François Natali | ded0348 | 2012-01-07 18:24:56 +0100 | [diff] [blame] | 420 | signaled = self._flag |
| 421 | if not signaled: |
| 422 | signaled = self._cond.wait(timeout) |
| 423 | return signaled |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 424 | finally: |
| 425 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 426 | |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 427 | |
| 428 | # A barrier class. Inspired in part by the pthread_barrier_* api and |
| 429 | # the CyclicBarrier class from Java. See |
| 430 | # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and |
| 431 | # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ |
| 432 | # CyclicBarrier.html |
| 433 | # for information. |
| 434 | # We maintain two main states, 'filling' and 'draining' enabling the barrier |
| 435 | # to be cyclic. Threads are not allowed into it until it has fully drained |
| 436 | # since the previous cycle. In addition, a 'resetting' state exists which is |
| 437 | # similar to 'draining' except that threads leave with a BrokenBarrierError, |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 438 | # and a 'broken' state in which all threads get the exception. |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 439 | class Barrier(_Verbose): |
| 440 | """ |
| 441 | Barrier. Useful for synchronizing a fixed number of threads |
| 442 | at known synchronization points. Threads block on 'wait()' and are |
| 443 | simultaneously once they have all made that call. |
| 444 | """ |
| 445 | def __init__(self, parties, action=None, timeout=None, verbose=None): |
| 446 | """ |
| 447 | Create a barrier, initialised to 'parties' threads. |
| 448 | 'action' is a callable which, when supplied, will be called |
| 449 | by one of the threads after they have all entered the |
| 450 | barrier and just prior to releasing them all. |
| 451 | If a 'timeout' is provided, it is uses as the default for |
| 452 | all subsequent 'wait()' calls. |
| 453 | """ |
| 454 | _Verbose.__init__(self, verbose) |
| 455 | self._cond = Condition(Lock()) |
| 456 | self._action = action |
| 457 | self._timeout = timeout |
| 458 | self._parties = parties |
| 459 | self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken |
| 460 | self._count = 0 |
| 461 | |
| 462 | def wait(self, timeout=None): |
| 463 | """ |
| 464 | Wait for the barrier. When the specified number of threads have |
| 465 | started waiting, they are all simultaneously awoken. If an 'action' |
| 466 | was provided for the barrier, one of the threads will have executed |
| 467 | that callback prior to returning. |
| 468 | Returns an individual index number from 0 to 'parties-1'. |
| 469 | """ |
| 470 | if timeout is None: |
| 471 | timeout = self._timeout |
| 472 | with self._cond: |
| 473 | self._enter() # Block while the barrier drains. |
| 474 | index = self._count |
| 475 | self._count += 1 |
| 476 | try: |
| 477 | if index + 1 == self._parties: |
| 478 | # We release the barrier |
| 479 | self._release() |
| 480 | else: |
| 481 | # We wait until someone releases us |
| 482 | self._wait(timeout) |
| 483 | return index |
| 484 | finally: |
| 485 | self._count -= 1 |
| 486 | # Wake up any threads waiting for barrier to drain. |
| 487 | self._exit() |
| 488 | |
| 489 | # Block until the barrier is ready for us, or raise an exception |
| 490 | # if it is broken. |
| 491 | def _enter(self): |
| 492 | while self._state in (-1, 1): |
| 493 | # It is draining or resetting, wait until done |
| 494 | self._cond.wait() |
| 495 | #see if the barrier is in a broken state |
| 496 | if self._state < 0: |
| 497 | raise BrokenBarrierError |
| 498 | assert self._state == 0 |
| 499 | |
| 500 | # Optionally run the 'action' and release the threads waiting |
| 501 | # in the barrier. |
| 502 | def _release(self): |
| 503 | try: |
| 504 | if self._action: |
| 505 | self._action() |
| 506 | # enter draining state |
| 507 | self._state = 1 |
| 508 | self._cond.notify_all() |
| 509 | except: |
| 510 | #an exception during the _action handler. Break and reraise |
| 511 | self._break() |
| 512 | raise |
| 513 | |
| 514 | # Wait in the barrier until we are relased. Raise an exception |
| 515 | # if the barrier is reset or broken. |
| 516 | def _wait(self, timeout): |
Kristján Valur Jónsson | 6331520 | 2010-11-18 12:46:39 +0000 | [diff] [blame] | 517 | if not self._cond.wait_for(lambda : self._state != 0, timeout): |
| 518 | #timed out. Break the barrier |
| 519 | self._break() |
| 520 | raise BrokenBarrierError |
| 521 | if self._state < 0: |
| 522 | raise BrokenBarrierError |
Kristján Valur Jónsson | 3be0003 | 2010-10-28 09:43:10 +0000 | [diff] [blame] | 523 | assert self._state == 1 |
| 524 | |
| 525 | # If we are the last thread to exit the barrier, signal any threads |
| 526 | # waiting for the barrier to drain. |
| 527 | def _exit(self): |
| 528 | if self._count == 0: |
| 529 | if self._state in (-1, 1): |
| 530 | #resetting or draining |
| 531 | self._state = 0 |
| 532 | self._cond.notify_all() |
| 533 | |
| 534 | def reset(self): |
| 535 | """ |
| 536 | Reset the barrier to the initial state. |
| 537 | Any threads currently waiting will get the BrokenBarrier exception |
| 538 | raised. |
| 539 | """ |
| 540 | with self._cond: |
| 541 | if self._count > 0: |
| 542 | if self._state == 0: |
| 543 | #reset the barrier, waking up threads |
| 544 | self._state = -1 |
| 545 | elif self._state == -2: |
| 546 | #was broken, set it to reset state |
| 547 | #which clears when the last thread exits |
| 548 | self._state = -1 |
| 549 | else: |
| 550 | self._state = 0 |
| 551 | self._cond.notify_all() |
| 552 | |
| 553 | def abort(self): |
| 554 | """ |
| 555 | Place the barrier into a 'broken' state. |
| 556 | Useful in case of error. Any currently waiting threads and |
| 557 | threads attempting to 'wait()' will have BrokenBarrierError |
| 558 | raised. |
| 559 | """ |
| 560 | with self._cond: |
| 561 | self._break() |
| 562 | |
| 563 | def _break(self): |
| 564 | # An internal error was detected. The barrier is set to |
| 565 | # a broken state all parties awakened. |
| 566 | self._state = -2 |
| 567 | self._cond.notify_all() |
| 568 | |
| 569 | @property |
| 570 | def parties(self): |
| 571 | """ |
| 572 | Return the number of threads required to trip the barrier. |
| 573 | """ |
| 574 | return self._parties |
| 575 | |
| 576 | @property |
| 577 | def n_waiting(self): |
| 578 | """ |
| 579 | Return the number of threads that are currently waiting at the barrier. |
| 580 | """ |
| 581 | # We don't need synchronization here since this is an ephemeral result |
| 582 | # anyway. It returns the correct value in the steady state. |
| 583 | if self._state == 0: |
| 584 | return self._count |
| 585 | return 0 |
| 586 | |
| 587 | @property |
| 588 | def broken(self): |
| 589 | """ |
| 590 | Return True if the barrier is in a broken state |
| 591 | """ |
| 592 | return self._state == -2 |
| 593 | |
| 594 | #exception raised by the Barrier class |
| 595 | class BrokenBarrierError(RuntimeError): pass |
| 596 | |
| 597 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 598 | # Helper to generate new thread names |
| 599 | _counter = 0 |
| 600 | def _newname(template="Thread-%d"): |
| 601 | global _counter |
| 602 | _counter = _counter + 1 |
| 603 | return template % _counter |
| 604 | |
| 605 | # Active thread administration |
| 606 | _active_limbo_lock = _allocate_lock() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 607 | _active = {} # maps thread id to Thread object |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 608 | _limbo = {} |
| 609 | |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 610 | # For debug and leak testing |
| 611 | _dangling = WeakSet() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 612 | |
| 613 | # Main class for threads |
| 614 | |
| 615 | class Thread(_Verbose): |
| 616 | |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 617 | __initialized = False |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 618 | # Need to store a reference to sys.exc_info for printing |
| 619 | # out exceptions when a thread tries to use a global var. during interp. |
| 620 | # shutdown and thus raises an exception about trying to perform some |
| 621 | # operation on/with a NoneType |
| 622 | __exc_info = _sys.exc_info |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 623 | # Keep sys.exc_clear too to clear the exception just before |
| 624 | # allowing .join() to return. |
| 625 | #XXX __exc_clear = _sys.exc_clear |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 626 | |
| 627 | def __init__(self, group=None, target=None, name=None, |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 628 | args=(), kwargs=None, verbose=None): |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 629 | assert group is None, "group argument must be None for now" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 630 | _Verbose.__init__(self, verbose) |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 631 | if kwargs is None: |
| 632 | kwargs = {} |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 633 | self._target = target |
| 634 | self._name = str(name or _newname()) |
| 635 | self._args = args |
| 636 | self._kwargs = kwargs |
| 637 | self._daemonic = self._set_daemon() |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 638 | self._ident = None |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 639 | self._started = Event() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 640 | self._stopped = False |
| 641 | self._block = Condition(Lock()) |
| 642 | self._initialized = True |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 643 | # sys.stderr is not stored in the class like |
| 644 | # sys.exc_info since it can be changed between instances |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 645 | self._stderr = _sys.stderr |
Antoine Pitrou | c081c0c | 2011-07-15 22:12:24 +0200 | [diff] [blame] | 646 | _dangling.add(self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 647 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 648 | def _reset_internal_locks(self): |
| 649 | # private! Called by _after_fork() to reset our internal locks as |
| 650 | # they may be in an invalid state leading to a deadlock or crash. |
| 651 | if hasattr(self, '_block'): # DummyThread deletes _block |
| 652 | self._block.__init__() |
| 653 | self._started._reset_internal_locks() |
| 654 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 655 | def _set_daemon(self): |
| 656 | # Overridden in _MainThread and _DummyThread |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 657 | return current_thread().daemon |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 658 | |
| 659 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 660 | assert self._initialized, "Thread.__init__() was not called" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 661 | status = "initial" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 662 | if self._started.is_set(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 663 | status = "started" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 664 | if self._stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 665 | status = "stopped" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 666 | if self._daemonic: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 667 | status += " daemon" |
| 668 | if self._ident is not None: |
| 669 | status += " %s" % self._ident |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 670 | return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 671 | |
| 672 | def start(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 673 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 674 | raise RuntimeError("thread.__init__() not called") |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 675 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 676 | if self._started.is_set(): |
Senthil Kumaran | fdd4d0f | 2010-04-06 03:30:18 +0000 | [diff] [blame] | 677 | raise RuntimeError("threads can only be started once") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 678 | if __debug__: |
| 679 | self._note("%s.start(): starting thread", self) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 680 | with _active_limbo_lock: |
| 681 | _limbo[self] = self |
Gregory P. Smith | 3fdd964 | 2010-02-28 18:57:46 +0000 | [diff] [blame] | 682 | try: |
| 683 | _start_new_thread(self._bootstrap, ()) |
| 684 | except Exception: |
| 685 | with _active_limbo_lock: |
| 686 | del _limbo[self] |
| 687 | raise |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 688 | self._started.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 689 | |
| 690 | def run(self): |
Christian Heimes | d3eb5a15 | 2008-02-24 00:38:49 +0000 | [diff] [blame] | 691 | try: |
| 692 | if self._target: |
| 693 | self._target(*self._args, **self._kwargs) |
| 694 | finally: |
| 695 | # Avoid a refcycle if the thread is running a function with |
| 696 | # an argument that has a member that points to the thread. |
| 697 | del self._target, self._args, self._kwargs |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 698 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 699 | def _bootstrap(self): |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 700 | # Wrapper around the real bootstrap code that ignores |
| 701 | # exceptions during interpreter cleanup. Those typically |
| 702 | # happen when a daemon thread wakes up at an unfortunate |
| 703 | # moment, finds the world around it destroyed, and raises some |
| 704 | # random exception *** while trying to report the exception in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 705 | # _bootstrap_inner() below ***. Those random exceptions |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 706 | # don't help anybody, and they confuse users, so we suppress |
| 707 | # them. We suppress them only when it appears that the world |
| 708 | # indeed has already been destroyed, so that exceptions in |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 709 | # _bootstrap_inner() during normal business hours are properly |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 710 | # reported. Also, we only suppress them for daemonic threads; |
| 711 | # if a non-daemonic encounters this, something else is wrong. |
| 712 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 713 | self._bootstrap_inner() |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 714 | except: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 715 | if self._daemonic and _sys is None: |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 716 | return |
| 717 | raise |
| 718 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 719 | def _set_ident(self): |
| 720 | self._ident = _get_ident() |
| 721 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 722 | def _bootstrap_inner(self): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 723 | try: |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 724 | self._set_ident() |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 725 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 726 | with _active_limbo_lock: |
| 727 | _active[self._ident] = self |
| 728 | del _limbo[self] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 729 | if __debug__: |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 730 | self._note("%s._bootstrap(): thread started", self) |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 731 | |
| 732 | if _trace_hook: |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 733 | self._note("%s._bootstrap(): registering trace hook", self) |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 734 | _sys.settrace(_trace_hook) |
| 735 | if _profile_hook: |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 736 | self._note("%s._bootstrap(): registering profile hook", self) |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 737 | _sys.setprofile(_profile_hook) |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 738 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 739 | try: |
| 740 | self.run() |
| 741 | except SystemExit: |
| 742 | if __debug__: |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 743 | self._note("%s._bootstrap(): raised SystemExit", self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 744 | except: |
| 745 | if __debug__: |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 746 | self._note("%s._bootstrap(): unhandled exception", self) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 747 | # If sys.stderr is no more (most likely from interpreter |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 748 | # shutdown) use self._stderr. Otherwise still use sys (as in |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 749 | # _sys) in case sys.stderr was redefined since the creation of |
| 750 | # self. |
| 751 | if _sys: |
| 752 | _sys.stderr.write("Exception in thread %s:\n%s\n" % |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 753 | (self.name, _format_exc())) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 754 | else: |
| 755 | # Do the best job possible w/o a huge amt. of code to |
| 756 | # approximate a traceback (code ideas from |
| 757 | # Lib/traceback.py) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 758 | exc_type, exc_value, exc_tb = self._exc_info() |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 759 | try: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 760 | print(( |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 761 | "Exception in thread " + self.name + |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 762 | " (most likely raised during interpreter shutdown):"), file=self._stderr) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 763 | print(( |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 764 | "Traceback (most recent call last):"), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 765 | while exc_tb: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 766 | print(( |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 767 | ' File "%s", line %s, in %s' % |
| 768 | (exc_tb.tb_frame.f_code.co_filename, |
| 769 | exc_tb.tb_lineno, |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 770 | exc_tb.tb_frame.f_code.co_name)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 771 | exc_tb = exc_tb.tb_next |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 772 | print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 773 | # Make sure that exc_tb gets deleted since it is a memory |
| 774 | # hog; deleting everything else is just for thoroughness |
| 775 | finally: |
| 776 | del exc_type, exc_value, exc_tb |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 777 | else: |
| 778 | if __debug__: |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 779 | self._note("%s._bootstrap(): normal return", self) |
Christian Heimes | bbe741d | 2008-03-28 10:53:29 +0000 | [diff] [blame] | 780 | finally: |
| 781 | # Prevent a race in |
| 782 | # test_threading.test_no_refcycle_through_target when |
| 783 | # the exception keeps the target alive past when we |
| 784 | # assert that it's dead. |
| 785 | #XXX self.__exc_clear() |
| 786 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 787 | finally: |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 788 | with _active_limbo_lock: |
| 789 | self._stop() |
| 790 | try: |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 791 | # We don't call self._delete() because it also |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 792 | # grabs _active_limbo_lock. |
| 793 | del _active[_get_ident()] |
| 794 | except: |
| 795 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 796 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 797 | def _stop(self): |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 798 | self._block.acquire() |
| 799 | self._stopped = True |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 800 | self._block.notify_all() |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 801 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 802 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 803 | def _delete(self): |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 804 | "Remove current thread from the dict of currently running threads." |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 805 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 806 | # Notes about running with _dummy_thread: |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 807 | # |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 808 | # 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] | 809 | # used (and thus this module is being used as an instance of |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 810 | # dummy_threading). _dummy_thread.get_ident() always returns -1 since |
| 811 | # there is only one thread if _dummy_thread is being used. Thus |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 812 | # len(_active) is always <= 1 here, and any Thread instance created |
| 813 | # overwrites the (if any) thread currently registered in _active. |
| 814 | # |
| 815 | # An instance of _MainThread is always created by 'threading'. This |
| 816 | # gets overwritten the instant an instance of Thread is created; both |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 817 | # threads return -1 from _dummy_thread.get_ident() and thus have the |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 818 | # same key in the dict. So when the _MainThread instance created by |
| 819 | # 'threading' tries to clean itself up when atexit calls this method |
| 820 | # it gets a KeyError if another Thread instance was created. |
| 821 | # |
| 822 | # This all means that KeyError from trying to delete something from |
| 823 | # _active if dummy_threading is being used is a red herring. But |
| 824 | # since it isn't if dummy_threading is *not* being used then don't |
| 825 | # hide the exception. |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 826 | |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 827 | try: |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 828 | with _active_limbo_lock: |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 829 | del _active[_get_ident()] |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 830 | # There must not be any python code between the previous line |
| 831 | # and after the lock is released. Otherwise a tracing function |
| 832 | # could try to acquire the lock again in the same thread, (in |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 833 | # current_thread()), and would block. |
Neal Norwitz | f5c7c2e | 2008-04-05 04:47:45 +0000 | [diff] [blame] | 834 | except KeyError: |
| 835 | if 'dummy_threading' not in _sys.modules: |
| 836 | raise |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 837 | |
| 838 | def join(self, timeout=None): |
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") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 841 | if not self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 842 | raise RuntimeError("cannot join thread before it is started") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 843 | if self is current_thread(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 844 | raise RuntimeError("cannot join current thread") |
| 845 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 846 | if __debug__: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 847 | if not self._stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 848 | self._note("%s.join(): waiting until thread stops", self) |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 849 | |
| 850 | self._block.acquire() |
| 851 | try: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 852 | if timeout is None: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 853 | while not self._stopped: |
| 854 | self._block.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 855 | if __debug__: |
| 856 | self._note("%s.join(): thread stopped", self) |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 857 | else: |
| 858 | deadline = _time() + timeout |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 859 | while not self._stopped: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 860 | delay = deadline - _time() |
| 861 | if delay <= 0: |
| 862 | if __debug__: |
| 863 | self._note("%s.join(): timed out", self) |
| 864 | break |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 865 | self._block.wait(delay) |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 866 | else: |
| 867 | if __debug__: |
| 868 | self._note("%s.join(): thread stopped", self) |
Christian Heimes | 969fe57 | 2008-01-25 11:23:10 +0000 | [diff] [blame] | 869 | finally: |
| 870 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 871 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 872 | @property |
| 873 | def name(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 874 | assert self._initialized, "Thread.__init__() not called" |
| 875 | return self._name |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 876 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 877 | @name.setter |
| 878 | def name(self, name): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 879 | assert self._initialized, "Thread.__init__() not called" |
| 880 | self._name = str(name) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 881 | |
Benjamin Peterson | 773c17b | 2008-08-18 16:45:31 +0000 | [diff] [blame] | 882 | @property |
| 883 | def ident(self): |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 884 | assert self._initialized, "Thread.__init__() not called" |
| 885 | return self._ident |
| 886 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 887 | def is_alive(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 888 | assert self._initialized, "Thread.__init__() not called" |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 889 | return self._started.is_set() and not self._stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 890 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 891 | isAlive = is_alive |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 892 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 893 | @property |
| 894 | def daemon(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 895 | assert self._initialized, "Thread.__init__() not called" |
| 896 | return self._daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 897 | |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 898 | @daemon.setter |
| 899 | def daemon(self, daemonic): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 900 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 901 | raise RuntimeError("Thread.__init__() not called") |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 902 | if self._started.is_set(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 903 | raise RuntimeError("cannot set daemon status of active thread"); |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 904 | self._daemonic = daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 905 | |
Benjamin Peterson | 6640d72 | 2008-08-18 18:16:46 +0000 | [diff] [blame] | 906 | def isDaemon(self): |
| 907 | return self.daemon |
| 908 | |
| 909 | def setDaemon(self, daemonic): |
| 910 | self.daemon = daemonic |
| 911 | |
| 912 | def getName(self): |
| 913 | return self.name |
| 914 | |
| 915 | def setName(self, name): |
| 916 | self.name = name |
| 917 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 918 | # The timer class was contributed by Itamar Shtull-Trauring |
| 919 | |
| 920 | def Timer(*args, **kwargs): |
| 921 | return _Timer(*args, **kwargs) |
| 922 | |
| 923 | class _Timer(Thread): |
| 924 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 925 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 926 | t = Timer(30.0, f, args=[], kwargs={}) |
| 927 | t.start() |
| 928 | t.cancel() # stop the timer's action if it's still waiting |
| 929 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 930 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 931 | def __init__(self, interval, function, args=[], kwargs={}): |
| 932 | Thread.__init__(self) |
| 933 | self.interval = interval |
| 934 | self.function = function |
| 935 | self.args = args |
| 936 | self.kwargs = kwargs |
| 937 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 938 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 939 | def cancel(self): |
| 940 | """Stop the timer if it hasn't finished yet""" |
| 941 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 942 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 943 | def run(self): |
| 944 | self.finished.wait(self.interval) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 945 | if not self.finished.is_set(): |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 946 | self.function(*self.args, **self.kwargs) |
| 947 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 948 | |
| 949 | # Special thread class to represent the main thread |
| 950 | # This is garbage collected through an exit handler |
| 951 | |
| 952 | class _MainThread(Thread): |
| 953 | |
| 954 | def __init__(self): |
| 955 | Thread.__init__(self, name="MainThread") |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 956 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 957 | self._set_ident() |
| 958 | with _active_limbo_lock: |
| 959 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 960 | |
| 961 | def _set_daemon(self): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 962 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 963 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 964 | def _exitfunc(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 965 | self._stop() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 966 | t = _pickSomeNonDaemonThread() |
| 967 | if t: |
| 968 | if __debug__: |
| 969 | self._note("%s: waiting for other threads", self) |
| 970 | while t: |
| 971 | t.join() |
| 972 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 973 | if __debug__: |
| 974 | self._note("%s: exiting", self) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 975 | self._delete() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 976 | |
| 977 | def _pickSomeNonDaemonThread(): |
| 978 | for t in enumerate(): |
Benjamin Peterson | fdbea96 | 2008-08-18 17:33:47 +0000 | [diff] [blame] | 979 | if not t.daemon and t.is_alive(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 980 | return t |
| 981 | return None |
| 982 | |
| 983 | |
| 984 | # Dummy thread class to represent threads not started here. |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 985 | # 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] | 986 | # If they invoke anything in threading.py that calls current_thread(), they |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 987 | # leave an entry in the _active dict forever after. |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 988 | # Their purpose is to return *something* from current_thread(). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 989 | # They are marked as daemon threads so we won't wait for them |
| 990 | # when we exit (conform previous semantics). |
| 991 | |
| 992 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 993 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 994 | def __init__(self): |
| 995 | Thread.__init__(self, name=_newname("Dummy-%d")) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 996 | |
Gregory P. Smith | 9bd4a24 | 2011-01-04 18:33:38 +0000 | [diff] [blame] | 997 | # Thread._block consumes an OS-level locking primitive, which |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 998 | # can never be used by a _DummyThread. Since a _DummyThread |
| 999 | # instance is immortal, that's bad, so release this resource. |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 1000 | del self._block |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 1001 | |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 1002 | self._started.set() |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1003 | self._set_ident() |
| 1004 | with _active_limbo_lock: |
| 1005 | _active[self._ident] = self |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1006 | |
| 1007 | def _set_daemon(self): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 1008 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1009 | |
Antoine Pitrou | 8e6e0fd | 2012-04-19 23:55:01 +0200 | [diff] [blame] | 1010 | def _stop(self): |
| 1011 | pass |
| 1012 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 1013 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 1014 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1015 | |
| 1016 | |
| 1017 | # Global API functions |
| 1018 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1019 | def current_thread(): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1020 | try: |
| 1021 | return _active[_get_ident()] |
| 1022 | except KeyError: |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1023 | ##print "current_thread(): no current thread for", _get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1024 | return _DummyThread() |
| 1025 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1026 | currentThread = current_thread |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1027 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 1028 | def active_count(): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1029 | with _active_limbo_lock: |
| 1030 | return len(_active) + len(_limbo) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1031 | |
Benjamin Peterson | b3085c9 | 2008-09-01 23:09:31 +0000 | [diff] [blame] | 1032 | activeCount = active_count |
Benjamin Peterson | f0923f5 | 2008-08-18 22:10:13 +0000 | [diff] [blame] | 1033 | |
Antoine Pitrou | bdec11f | 2009-11-05 13:49:14 +0000 | [diff] [blame] | 1034 | def _enumerate(): |
| 1035 | # Same as enumerate(), but without the lock. Internal use only. |
| 1036 | return list(_active.values()) + list(_limbo.values()) |
| 1037 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1038 | def enumerate(): |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1039 | with _active_limbo_lock: |
| 1040 | return list(_active.values()) + list(_limbo.values()) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1041 | |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 1042 | from _thread import stack_size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1043 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1044 | # Create the main thread object, |
| 1045 | # and make it available for the interpreter |
| 1046 | # (Py_Main) as threading._shutdown. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1047 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1048 | _shutdown = _MainThread()._exitfunc |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1049 | |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 1050 | # get thread-local implementation, either from the thread |
| 1051 | # module, or from the python fallback |
| 1052 | |
| 1053 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 1054 | from _thread import _local as local |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 1055 | except ImportError: |
| 1056 | from _threading_local import local |
| 1057 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 1058 | |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1059 | def _after_fork(): |
| 1060 | # This function is called by Python/ceval.c:PyEval_ReInitThreads which |
| 1061 | # is called from PyOS_AfterFork. Here we cleanup threading module state |
| 1062 | # that should not exist after a fork. |
| 1063 | |
| 1064 | # Reset _active_limbo_lock, in case we forked while the lock was held |
| 1065 | # by another (non-forked) thread. http://bugs.python.org/issue874900 |
| 1066 | global _active_limbo_lock |
| 1067 | _active_limbo_lock = _allocate_lock() |
| 1068 | |
| 1069 | # fork() only copied the current thread; clear references to others. |
| 1070 | new_active = {} |
| 1071 | current = current_thread() |
| 1072 | with _active_limbo_lock: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 1073 | for thread in _active.values(): |
Charles-François Natali | 6d5f9e7 | 2011-12-18 18:35:09 +0100 | [diff] [blame] | 1074 | # Any lock/condition variable may be currently locked or in an |
| 1075 | # invalid state, so we reinitialize them. |
| 1076 | thread._reset_internal_locks() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1077 | if thread is current: |
Antoine Pitrou | 5fe291f | 2008-09-06 23:00:03 +0000 | [diff] [blame] | 1078 | # There is only one active thread. We reset the ident to |
| 1079 | # its new value since it can have changed. |
| 1080 | ident = _get_ident() |
| 1081 | thread._ident = ident |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1082 | new_active[ident] = thread |
| 1083 | else: |
| 1084 | # All the others are already stopped. |
Charles-François Natali | 6d5f9e7 | 2011-12-18 18:35:09 +0100 | [diff] [blame] | 1085 | thread._stop() |
Jesse Noller | a851397 | 2008-07-17 16:49:17 +0000 | [diff] [blame] | 1086 | |
| 1087 | _limbo.clear() |
| 1088 | _active.clear() |
| 1089 | _active.update(new_active) |
| 1090 | assert len(_active) == 1 |