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