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 |
| 4 | |
| 5 | try: |
| 6 | import thread |
| 7 | except ImportError: |
| 8 | del _sys.modules[__name__] |
| 9 | raise |
| 10 | |
Fred Drake | a872595 | 2002-12-30 23:32:50 +0000 | [diff] [blame] | 11 | from time import time as _time, sleep as _sleep |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 12 | from traceback import format_exc as _format_exc |
Raymond Hettinger | 756b3f3 | 2004-01-29 06:37:52 +0000 | [diff] [blame] | 13 | from collections import deque |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 14 | |
| 15 | # Rename some stuff so "from threading import *" is safe |
Guido van Rossum | c262a1f | 2002-12-30 21:59:55 +0000 | [diff] [blame] | 16 | __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', |
Tim Peters | 685e697 | 2003-06-29 16:50:06 +0000 | [diff] [blame] | 17 | 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 18 | 'Timer', 'setprofile', 'settrace', 'local', 'stack_size'] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 19 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 20 | _start_new_thread = thread.start_new_thread |
| 21 | _allocate_lock = thread.allocate_lock |
| 22 | _get_ident = thread.get_ident |
Jeremy Hylton | b5fc749 | 2000-06-01 01:17:17 +0000 | [diff] [blame] | 23 | ThreadError = thread.error |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 24 | del thread |
| 25 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 26 | |
Tim Peters | 59aba12 | 2003-07-01 20:01:55 +0000 | [diff] [blame] | 27 | # Debug support (adapted from ihooks.py). |
| 28 | # All the major classes here derive from _Verbose. We force that to |
| 29 | # be a new-style class so that all the major classes here are new-style. |
| 30 | # This helps debugging (type(instance) is more revealing for instances |
| 31 | # of new-style classes). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 32 | |
Tim Peters | 0939fac | 2003-07-01 19:28:44 +0000 | [diff] [blame] | 33 | _VERBOSE = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 34 | |
| 35 | if __debug__: |
| 36 | |
Tim Peters | 59aba12 | 2003-07-01 20:01:55 +0000 | [diff] [blame] | 37 | class _Verbose(object): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 38 | |
| 39 | def __init__(self, verbose=None): |
| 40 | if verbose is None: |
| 41 | verbose = _VERBOSE |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 42 | self._verbose = verbose |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 43 | |
| 44 | def _note(self, format, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 45 | if self._verbose: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 46 | format = format % args |
| 47 | format = "%s: %s\n" % ( |
| 48 | currentThread().getName(), format) |
| 49 | _sys.stderr.write(format) |
| 50 | |
| 51 | else: |
| 52 | # Disable this when using "python -O" |
Tim Peters | 59aba12 | 2003-07-01 20:01:55 +0000 | [diff] [blame] | 53 | class _Verbose(object): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 54 | def __init__(self, verbose=None): |
| 55 | pass |
| 56 | def _note(self, *args): |
| 57 | pass |
| 58 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 59 | # Support for profile and trace hooks |
| 60 | |
| 61 | _profile_hook = None |
| 62 | _trace_hook = None |
| 63 | |
| 64 | def setprofile(func): |
| 65 | global _profile_hook |
| 66 | _profile_hook = func |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 67 | |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 68 | def settrace(func): |
| 69 | global _trace_hook |
| 70 | _trace_hook = func |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 71 | |
| 72 | # Synchronization classes |
| 73 | |
| 74 | Lock = _allocate_lock |
| 75 | |
| 76 | def RLock(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 77 | return _RLock(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 78 | |
| 79 | class _RLock(_Verbose): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 80 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 81 | def __init__(self, verbose=None): |
| 82 | _Verbose.__init__(self, verbose) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 83 | self._block = _allocate_lock() |
| 84 | self._owner = None |
| 85 | self._count = 0 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 86 | |
| 87 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 88 | owner = self._owner |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 89 | return "<%s(%s, %d)>" % ( |
| 90 | self.__class__.__name__, |
Guido van Rossum | 806c246 | 2007-08-06 23:33:07 +0000 | [diff] [blame] | 91 | owner and owner.getName(), |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 92 | self._count) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 93 | |
| 94 | def acquire(self, blocking=1): |
| 95 | me = currentThread() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 96 | if self._owner is me: |
| 97 | self._count = self._count + 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 98 | if __debug__: |
| 99 | self._note("%s.acquire(%s): recursive success", self, blocking) |
| 100 | return 1 |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 101 | rc = self._block.acquire(blocking) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 102 | if rc: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 103 | self._owner = me |
| 104 | self._count = 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 105 | if __debug__: |
Brett Cannon | 90cece7 | 2005-01-27 22:48:30 +0000 | [diff] [blame] | 106 | self._note("%s.acquire(%s): initial success", self, blocking) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 107 | else: |
| 108 | if __debug__: |
| 109 | self._note("%s.acquire(%s): failure", self, blocking) |
| 110 | return rc |
| 111 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 112 | __enter__ = acquire |
| 113 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 114 | def release(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 115 | if self._owner is not currentThread(): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 116 | raise RuntimeError("cannot release un-aquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 117 | self._count = count = self._count - 1 |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 118 | if not count: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 119 | self._owner = None |
| 120 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 121 | if __debug__: |
| 122 | self._note("%s.release(): final release", self) |
| 123 | else: |
| 124 | if __debug__: |
| 125 | self._note("%s.release(): non-final release", self) |
| 126 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 127 | def __exit__(self, t, v, tb): |
| 128 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 129 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 130 | # Internal methods used by condition variables |
| 131 | |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame] | 132 | def _acquire_restore(self, state): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 133 | self._block.acquire() |
| 134 | self._count, self._owner = state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 135 | if __debug__: |
| 136 | self._note("%s._acquire_restore()", self) |
| 137 | |
| 138 | def _release_save(self): |
| 139 | if __debug__: |
| 140 | self._note("%s._release_save()", self) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 141 | count = self._count |
| 142 | self._count = 0 |
| 143 | owner = self._owner |
| 144 | self._owner = None |
| 145 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 146 | return (count, owner) |
| 147 | |
| 148 | def _is_owned(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 149 | return self._owner is currentThread() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 150 | |
| 151 | |
| 152 | def Condition(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 153 | return _Condition(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 154 | |
| 155 | class _Condition(_Verbose): |
| 156 | |
| 157 | def __init__(self, lock=None, verbose=None): |
| 158 | _Verbose.__init__(self, verbose) |
| 159 | if lock is None: |
| 160 | lock = RLock() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 161 | self._lock = lock |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 162 | # Export the lock's acquire() and release() methods |
| 163 | self.acquire = lock.acquire |
| 164 | self.release = lock.release |
| 165 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 166 | # these override the default implementations (which just call |
| 167 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 168 | try: |
| 169 | self._release_save = lock._release_save |
| 170 | except AttributeError: |
| 171 | pass |
| 172 | try: |
| 173 | self._acquire_restore = lock._acquire_restore |
| 174 | except AttributeError: |
| 175 | pass |
| 176 | try: |
| 177 | self._is_owned = lock._is_owned |
| 178 | except AttributeError: |
| 179 | pass |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 180 | self._waiters = [] |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 181 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 182 | def __enter__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 183 | return self._lock.__enter__() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 184 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 185 | def __exit__(self, *args): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 186 | return self._lock.__exit__(*args) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 187 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 188 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 189 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 190 | |
| 191 | def _release_save(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 192 | self._lock.release() # No state to save |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 193 | |
| 194 | def _acquire_restore(self, x): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 195 | self._lock.acquire() # Ignore saved state |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 196 | |
| 197 | def _is_owned(self): |
Jeremy Hylton | 39c12bf | 2002-08-14 17:46:40 +0000 | [diff] [blame] | 198 | # Return True if lock is owned by currentThread. |
Jeremy Hylton | af7fde7 | 2002-08-14 17:43:59 +0000 | [diff] [blame] | 199 | # 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] | 200 | if self._lock.acquire(0): |
| 201 | self._lock.release() |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 202 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 203 | else: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 204 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 205 | |
| 206 | def wait(self, timeout=None): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 207 | if not self._is_owned(): |
| 208 | raise RuntimeError("cannot wait on un-aquired lock") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 209 | waiter = _allocate_lock() |
| 210 | waiter.acquire() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 211 | self._waiters.append(waiter) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 212 | saved_state = self._release_save() |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 213 | try: # restore state no matter what (e.g., KeyboardInterrupt) |
| 214 | if timeout is None: |
| 215 | waiter.acquire() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 216 | if __debug__: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 217 | self._note("%s.wait(): got it", self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 218 | else: |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 219 | # Balancing act: We can't afford a pure busy loop, so we |
| 220 | # have to sleep; but if we sleep the whole timeout time, |
| 221 | # we'll be unresponsive. The scheme here sleeps very |
| 222 | # little at first, longer as time goes on, but never longer |
| 223 | # than 20 times per second (or the timeout time remaining). |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 224 | endtime = _time() + timeout |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 225 | delay = 0.0005 # 500 us -> initial delay of 1 ms |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 226 | while True: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 227 | gotit = waiter.acquire(0) |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 228 | if gotit: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 229 | break |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 230 | remaining = endtime - _time() |
| 231 | if remaining <= 0: |
| 232 | break |
| 233 | delay = min(delay * 2, remaining, .05) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 234 | _sleep(delay) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 235 | if not gotit: |
| 236 | if __debug__: |
| 237 | self._note("%s.wait(%s): timed out", self, timeout) |
| 238 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 239 | self._waiters.remove(waiter) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 240 | except ValueError: |
| 241 | pass |
| 242 | else: |
| 243 | if __debug__: |
| 244 | self._note("%s.wait(%s): got it", self, timeout) |
| 245 | finally: |
| 246 | self._acquire_restore(saved_state) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 247 | |
| 248 | def notify(self, n=1): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 249 | if not self._is_owned(): |
| 250 | raise RuntimeError("cannot notify on un-aquired lock") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 251 | __waiters = self._waiters |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 252 | waiters = __waiters[:n] |
| 253 | if not waiters: |
| 254 | if __debug__: |
| 255 | self._note("%s.notify(): no waiters", self) |
| 256 | return |
| 257 | self._note("%s.notify(): notifying %d waiter%s", self, n, |
| 258 | n!=1 and "s" or "") |
| 259 | for waiter in waiters: |
| 260 | waiter.release() |
| 261 | try: |
| 262 | __waiters.remove(waiter) |
| 263 | except ValueError: |
| 264 | pass |
| 265 | |
| 266 | def notifyAll(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 267 | self.notify(len(self._waiters)) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 268 | |
| 269 | |
| 270 | def Semaphore(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 271 | return _Semaphore(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 272 | |
| 273 | class _Semaphore(_Verbose): |
| 274 | |
Andrew M. Kuchling | 39d3bfc | 2000-02-29 00:10:24 +0000 | [diff] [blame] | 275 | # 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] | 276 | |
| 277 | def __init__(self, value=1, verbose=None): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 278 | if value < 0: |
| 279 | raise ValueError("semaphore initial value must be >= 0") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 280 | _Verbose.__init__(self, verbose) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 281 | self._cond = Condition(Lock()) |
| 282 | self._value = value |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 283 | |
| 284 | def acquire(self, blocking=1): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 285 | rc = False |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 286 | self._cond.acquire() |
| 287 | while self._value == 0: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 288 | if not blocking: |
| 289 | break |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 290 | if __debug__: |
| 291 | self._note("%s.acquire(%s): blocked waiting, value=%s", |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 292 | self, blocking, self._value) |
| 293 | self._cond.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 294 | else: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 295 | self._value = self._value - 1 |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 296 | if __debug__: |
Skip Montanaro | ae8454a | 2001-08-19 05:53:47 +0000 | [diff] [blame] | 297 | self._note("%s.acquire: success, value=%s", |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 298 | self, self._value) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 299 | rc = True |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 300 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 301 | return rc |
| 302 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 303 | __enter__ = acquire |
| 304 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 305 | def release(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 306 | self._cond.acquire() |
| 307 | self._value = self._value + 1 |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 308 | if __debug__: |
Skip Montanaro | ae8454a | 2001-08-19 05:53:47 +0000 | [diff] [blame] | 309 | self._note("%s.release: success, value=%s", |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 310 | self, self._value) |
| 311 | self._cond.notify() |
| 312 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 313 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 314 | def __exit__(self, t, v, tb): |
| 315 | self.release() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 316 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 317 | |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 318 | def BoundedSemaphore(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 319 | return _BoundedSemaphore(*args, **kwargs) |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 320 | |
| 321 | class _BoundedSemaphore(_Semaphore): |
| 322 | """Semaphore that checks that # releases is <= # acquires""" |
| 323 | def __init__(self, value=1, verbose=None): |
| 324 | _Semaphore.__init__(self, value, verbose) |
| 325 | self._initial_value = value |
| 326 | |
| 327 | def release(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 328 | if self._value >= self._initial_value: |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 329 | raise ValueError, "Semaphore released too many times" |
| 330 | return _Semaphore.release(self) |
| 331 | |
| 332 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 333 | def Event(*args, **kwargs): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 334 | return _Event(*args, **kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 335 | |
| 336 | class _Event(_Verbose): |
| 337 | |
| 338 | # After Tim Peters' event class (without is_posted()) |
| 339 | |
| 340 | def __init__(self, verbose=None): |
| 341 | _Verbose.__init__(self, verbose) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 342 | self._cond = Condition(Lock()) |
| 343 | self._flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 344 | |
| 345 | def isSet(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 346 | return self._flag |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 347 | |
| 348 | def set(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 349 | self._cond.acquire() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 350 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 351 | self._flag = True |
| 352 | self._cond.notifyAll() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 353 | finally: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 354 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 355 | |
| 356 | def clear(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 357 | self._cond.acquire() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 358 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 359 | self._flag = False |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 360 | finally: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 361 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 362 | |
| 363 | def wait(self, timeout=None): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 364 | self._cond.acquire() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 365 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 366 | if not self._flag: |
| 367 | self._cond.wait(timeout) |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 368 | finally: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 369 | self._cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 370 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 371 | # Helper to generate new thread names |
| 372 | _counter = 0 |
| 373 | def _newname(template="Thread-%d"): |
| 374 | global _counter |
| 375 | _counter = _counter + 1 |
| 376 | return template % _counter |
| 377 | |
| 378 | # Active thread administration |
| 379 | _active_limbo_lock = _allocate_lock() |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 380 | _active = {} # maps thread id to Thread object |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 381 | _limbo = {} |
| 382 | |
| 383 | |
| 384 | # Main class for threads |
| 385 | |
| 386 | class Thread(_Verbose): |
| 387 | |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 388 | __initialized = False |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 389 | # Need to store a reference to sys.exc_info for printing |
| 390 | # out exceptions when a thread tries to use a global var. during interp. |
| 391 | # shutdown and thus raises an exception about trying to perform some |
| 392 | # operation on/with a NoneType |
| 393 | __exc_info = _sys.exc_info |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 394 | |
| 395 | def __init__(self, group=None, target=None, name=None, |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 396 | args=(), kwargs=None, verbose=None): |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 397 | assert group is None, "group argument must be None for now" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 398 | _Verbose.__init__(self, verbose) |
Georg Brandl | a4a8b82 | 2005-07-15 09:13:21 +0000 | [diff] [blame] | 399 | if kwargs is None: |
| 400 | kwargs = {} |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 401 | self._target = target |
| 402 | self._name = str(name or _newname()) |
| 403 | self._args = args |
| 404 | self._kwargs = kwargs |
| 405 | self._daemonic = self._set_daemon() |
| 406 | self._started = False |
| 407 | self._stopped = False |
| 408 | self._block = Condition(Lock()) |
| 409 | self._initialized = True |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 410 | # sys.stderr is not stored in the class like |
| 411 | # sys.exc_info since it can be changed between instances |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 412 | self._stderr = _sys.stderr |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 413 | |
| 414 | def _set_daemon(self): |
| 415 | # Overridden in _MainThread and _DummyThread |
| 416 | return currentThread().isDaemon() |
| 417 | |
| 418 | def __repr__(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 419 | assert self._initialized, "Thread.__init__() was not called" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 420 | status = "initial" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 421 | if self._started: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 422 | status = "started" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 423 | if self._stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 424 | status = "stopped" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 425 | if self._daemonic: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 426 | status = status + " daemon" |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 427 | return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 428 | |
| 429 | def start(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 430 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 431 | raise RuntimeError("thread.__init__() not called") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 432 | if self._started: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 433 | raise RuntimeError("thread already started") |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 434 | if __debug__: |
| 435 | self._note("%s.start(): starting thread", self) |
| 436 | _active_limbo_lock.acquire() |
| 437 | _limbo[self] = self |
| 438 | _active_limbo_lock.release() |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 439 | _start_new_thread(self._bootstrap, ()) |
| 440 | self._started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 441 | _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack) |
| 442 | |
| 443 | def run(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 444 | if self._target: |
| 445 | self._target(*self._args, **self._kwargs) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 446 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 447 | def _bootstrap(self): |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 448 | # Wrapper around the real bootstrap code that ignores |
| 449 | # exceptions during interpreter cleanup. Those typically |
| 450 | # happen when a daemon thread wakes up at an unfortunate |
| 451 | # moment, finds the world around it destroyed, and raises some |
| 452 | # random exception *** while trying to report the exception in |
| 453 | # __bootstrap_inner() below ***. Those random exceptions |
| 454 | # don't help anybody, and they confuse users, so we suppress |
| 455 | # them. We suppress them only when it appears that the world |
| 456 | # indeed has already been destroyed, so that exceptions in |
| 457 | # __bootstrap_inner() during normal business hours are properly |
| 458 | # reported. Also, we only suppress them for daemonic threads; |
| 459 | # if a non-daemonic encounters this, something else is wrong. |
| 460 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 461 | self._bootstrap_inner() |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 462 | except: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 463 | if self._daemonic and _sys is None: |
Guido van Rossum | 61e21b5 | 2007-08-20 19:06:03 +0000 | [diff] [blame] | 464 | return |
| 465 | raise |
| 466 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 467 | def _bootstrap_inner(self): |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 468 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 469 | self._started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 470 | _active_limbo_lock.acquire() |
| 471 | _active[_get_ident()] = self |
| 472 | del _limbo[self] |
| 473 | _active_limbo_lock.release() |
| 474 | if __debug__: |
| 475 | self._note("%s.__bootstrap(): thread started", self) |
Jeremy Hylton | bfccb35 | 2003-06-29 16:58:41 +0000 | [diff] [blame] | 476 | |
| 477 | if _trace_hook: |
| 478 | self._note("%s.__bootstrap(): registering trace hook", self) |
| 479 | _sys.settrace(_trace_hook) |
| 480 | if _profile_hook: |
| 481 | self._note("%s.__bootstrap(): registering profile hook", self) |
| 482 | _sys.setprofile(_profile_hook) |
Tim Peters | d1b108b | 2003-06-29 17:24:17 +0000 | [diff] [blame] | 483 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 484 | try: |
| 485 | self.run() |
| 486 | except SystemExit: |
| 487 | if __debug__: |
| 488 | self._note("%s.__bootstrap(): raised SystemExit", self) |
| 489 | except: |
| 490 | if __debug__: |
| 491 | self._note("%s.__bootstrap(): unhandled exception", self) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 492 | # If sys.stderr is no more (most likely from interpreter |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 493 | # shutdown) use self._stderr. Otherwise still use sys (as in |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 494 | # _sys) in case sys.stderr was redefined since the creation of |
| 495 | # self. |
| 496 | if _sys: |
| 497 | _sys.stderr.write("Exception in thread %s:\n%s\n" % |
| 498 | (self.getName(), _format_exc())) |
| 499 | else: |
| 500 | # Do the best job possible w/o a huge amt. of code to |
| 501 | # approximate a traceback (code ideas from |
| 502 | # Lib/traceback.py) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 503 | exc_type, exc_value, exc_tb = self._exc_info() |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 504 | try: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 505 | print(( |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 506 | "Exception in thread " + self.getName() + |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 507 | " (most likely raised during interpreter shutdown):"), file=self._stderr) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 508 | print(( |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 509 | "Traceback (most recent call last):"), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 510 | while exc_tb: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 511 | print(( |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 512 | ' File "%s", line %s, in %s' % |
| 513 | (exc_tb.tb_frame.f_code.co_filename, |
| 514 | exc_tb.tb_lineno, |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 515 | exc_tb.tb_frame.f_code.co_name)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 516 | exc_tb = exc_tb.tb_next |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 517 | print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) |
Brett Cannon | cc4e935 | 2004-07-03 03:52:35 +0000 | [diff] [blame] | 518 | # Make sure that exc_tb gets deleted since it is a memory |
| 519 | # hog; deleting everything else is just for thoroughness |
| 520 | finally: |
| 521 | del exc_type, exc_value, exc_tb |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 522 | else: |
| 523 | if __debug__: |
| 524 | self._note("%s.__bootstrap(): normal return", self) |
| 525 | finally: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 526 | self._stop() |
Guido van Rossum | f21b2aa | 2001-12-28 22:07:09 +0000 | [diff] [blame] | 527 | try: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 528 | self._delete() |
Guido van Rossum | f21b2aa | 2001-12-28 22:07:09 +0000 | [diff] [blame] | 529 | except: |
| 530 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 531 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 532 | def _stop(self): |
| 533 | self._block.acquire() |
| 534 | self._stopped = True |
| 535 | self._block.notifyAll() |
| 536 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 537 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 538 | def _delete(self): |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 539 | "Remove current thread from the dict of currently running threads." |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 540 | |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 541 | # Notes about running with dummy_thread: |
| 542 | # |
| 543 | # Must take care to not raise an exception if dummy_thread is being |
| 544 | # used (and thus this module is being used as an instance of |
| 545 | # dummy_threading). dummy_thread.get_ident() always returns -1 since |
| 546 | # there is only one thread if dummy_thread is being used. Thus |
| 547 | # len(_active) is always <= 1 here, and any Thread instance created |
| 548 | # overwrites the (if any) thread currently registered in _active. |
| 549 | # |
| 550 | # An instance of _MainThread is always created by 'threading'. This |
| 551 | # gets overwritten the instant an instance of Thread is created; both |
| 552 | # threads return -1 from dummy_thread.get_ident() and thus have the |
| 553 | # same key in the dict. So when the _MainThread instance created by |
| 554 | # 'threading' tries to clean itself up when atexit calls this method |
| 555 | # it gets a KeyError if another Thread instance was created. |
| 556 | # |
| 557 | # This all means that KeyError from trying to delete something from |
| 558 | # _active if dummy_threading is being used is a red herring. But |
| 559 | # since it isn't if dummy_threading is *not* being used then don't |
| 560 | # hide the exception. |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 561 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 562 | _active_limbo_lock.acquire() |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 563 | try: |
Brett Cannon | 8b3d92a | 2004-07-21 02:21:58 +0000 | [diff] [blame] | 564 | try: |
| 565 | del _active[_get_ident()] |
| 566 | except KeyError: |
Tim Peters | 2142993 | 2004-07-21 03:36:52 +0000 | [diff] [blame] | 567 | if 'dummy_threading' not in _sys.modules: |
| 568 | raise |
| 569 | finally: |
| 570 | _active_limbo_lock.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 571 | |
| 572 | def join(self, timeout=None): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 573 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 574 | raise RuntimeError("Thread.__init__() not called") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 575 | if not self._started: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 576 | raise RuntimeError("cannot join thread before it is started") |
| 577 | if self is currentThread(): |
| 578 | raise RuntimeError("cannot join current thread") |
| 579 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 580 | if __debug__: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 581 | if not self._stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 582 | self._note("%s.join(): waiting until thread stops", self) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 583 | self._block.acquire() |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 584 | try: |
| 585 | if timeout is None: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 586 | while not self._stopped: |
| 587 | self._block.wait() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 588 | if __debug__: |
| 589 | self._note("%s.join(): thread stopped", self) |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 590 | else: |
| 591 | deadline = _time() + timeout |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 592 | while not self._stopped: |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 593 | delay = deadline - _time() |
| 594 | if delay <= 0: |
| 595 | if __debug__: |
| 596 | self._note("%s.join(): timed out", self) |
| 597 | break |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 598 | self._block.wait(delay) |
Brett Cannon | ad07ff2 | 2005-11-23 02:15:50 +0000 | [diff] [blame] | 599 | else: |
| 600 | if __debug__: |
| 601 | self._note("%s.join(): thread stopped", self) |
| 602 | finally: |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 603 | self._block.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 604 | |
| 605 | def getName(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 606 | assert self._initialized, "Thread.__init__() not called" |
| 607 | return self._name |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 608 | |
| 609 | def setName(self, name): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 610 | assert self._initialized, "Thread.__init__() not called" |
| 611 | self._name = str(name) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 612 | |
| 613 | def isAlive(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 614 | assert self._initialized, "Thread.__init__() not called" |
| 615 | return self._started and not self._stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 616 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 617 | def isDaemon(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 618 | assert self._initialized, "Thread.__init__() not called" |
| 619 | return self._daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 620 | |
| 621 | def setDaemon(self, daemonic): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 622 | if not self._initialized: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 623 | raise RuntimeError("Thread.__init__() not called") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 624 | if self._started: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 625 | raise RuntimeError("cannot set daemon status of active thread"); |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 626 | self._daemonic = daemonic |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 627 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 628 | # The timer class was contributed by Itamar Shtull-Trauring |
| 629 | |
| 630 | def Timer(*args, **kwargs): |
| 631 | return _Timer(*args, **kwargs) |
| 632 | |
| 633 | class _Timer(Thread): |
| 634 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 635 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 636 | t = Timer(30.0, f, args=[], kwargs={}) |
| 637 | t.start() |
| 638 | t.cancel() # stop the timer's action if it's still waiting |
| 639 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 640 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 641 | def __init__(self, interval, function, args=[], kwargs={}): |
| 642 | Thread.__init__(self) |
| 643 | self.interval = interval |
| 644 | self.function = function |
| 645 | self.args = args |
| 646 | self.kwargs = kwargs |
| 647 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 648 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 649 | def cancel(self): |
| 650 | """Stop the timer if it hasn't finished yet""" |
| 651 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 652 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 653 | def run(self): |
| 654 | self.finished.wait(self.interval) |
| 655 | if not self.finished.isSet(): |
| 656 | self.function(*self.args, **self.kwargs) |
| 657 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 658 | |
| 659 | # Special thread class to represent the main thread |
| 660 | # This is garbage collected through an exit handler |
| 661 | |
| 662 | class _MainThread(Thread): |
| 663 | |
| 664 | def __init__(self): |
| 665 | Thread.__init__(self, name="MainThread") |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 666 | self._started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 667 | _active_limbo_lock.acquire() |
| 668 | _active[_get_ident()] = self |
| 669 | _active_limbo_lock.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 670 | |
| 671 | def _set_daemon(self): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 672 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 673 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 674 | def _exitfunc(self): |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 675 | self._stop() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 676 | t = _pickSomeNonDaemonThread() |
| 677 | if t: |
| 678 | if __debug__: |
| 679 | self._note("%s: waiting for other threads", self) |
| 680 | while t: |
| 681 | t.join() |
| 682 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 683 | if __debug__: |
| 684 | self._note("%s: exiting", self) |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 685 | self._delete() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 686 | |
| 687 | def _pickSomeNonDaemonThread(): |
| 688 | for t in enumerate(): |
| 689 | if not t.isDaemon() and t.isAlive(): |
| 690 | return t |
| 691 | return None |
| 692 | |
| 693 | |
| 694 | # Dummy thread class to represent threads not started here. |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 695 | # These aren't garbage collected when they die, nor can they be waited for. |
| 696 | # If they invoke anything in threading.py that calls currentThread(), they |
| 697 | # leave an entry in the _active dict forever after. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 698 | # Their purpose is to return *something* from currentThread(). |
| 699 | # They are marked as daemon threads so we won't wait for them |
| 700 | # when we exit (conform previous semantics). |
| 701 | |
| 702 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 703 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 704 | def __init__(self): |
| 705 | Thread.__init__(self, name=_newname("Dummy-%d")) |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 706 | |
| 707 | # Thread.__block consumes an OS-level locking primitive, which |
| 708 | # can never be used by a _DummyThread. Since a _DummyThread |
| 709 | # instance is immortal, that's bad, so release this resource. |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 710 | del self._block |
Tim Peters | 711906e | 2005-01-08 07:30:42 +0000 | [diff] [blame] | 711 | |
Guido van Rossum | d064899 | 2007-08-20 19:25:41 +0000 | [diff] [blame] | 712 | self._started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 713 | _active_limbo_lock.acquire() |
| 714 | _active[_get_ident()] = self |
| 715 | _active_limbo_lock.release() |
| 716 | |
| 717 | def _set_daemon(self): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 718 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 719 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 720 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 721 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 722 | |
| 723 | |
| 724 | # Global API functions |
| 725 | |
| 726 | def currentThread(): |
| 727 | try: |
| 728 | return _active[_get_ident()] |
| 729 | except KeyError: |
Guido van Rossum | 5080b33 | 2000-12-15 20:08:39 +0000 | [diff] [blame] | 730 | ##print "currentThread(): no current thread for", _get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 731 | return _DummyThread() |
| 732 | |
| 733 | def activeCount(): |
| 734 | _active_limbo_lock.acquire() |
| 735 | count = len(_active) + len(_limbo) |
| 736 | _active_limbo_lock.release() |
| 737 | return count |
| 738 | |
| 739 | def enumerate(): |
| 740 | _active_limbo_lock.acquire() |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 741 | active = list(_active.values()) + list(_limbo.values()) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 742 | _active_limbo_lock.release() |
| 743 | return active |
| 744 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 745 | from thread import stack_size |
| 746 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 747 | # Create the main thread object, |
| 748 | # and make it available for the interpreter |
| 749 | # (Py_Main) as threading._shutdown. |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 750 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 751 | _shutdown = _MainThread()._exitfunc |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 752 | |
Jim Fulton | d15dc06 | 2004-07-14 19:11:50 +0000 | [diff] [blame] | 753 | # get thread-local implementation, either from the thread |
| 754 | # module, or from the python fallback |
| 755 | |
| 756 | try: |
| 757 | from thread import _local as local |
| 758 | except ImportError: |
| 759 | from _threading_local import local |
| 760 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 761 | |
| 762 | # Self-test code |
| 763 | |
| 764 | def _test(): |
| 765 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 766 | class BoundedQueue(_Verbose): |
| 767 | |
| 768 | def __init__(self, limit): |
| 769 | _Verbose.__init__(self) |
| 770 | self.mon = RLock() |
| 771 | self.rc = Condition(self.mon) |
| 772 | self.wc = Condition(self.mon) |
| 773 | self.limit = limit |
Raymond Hettinger | 756b3f3 | 2004-01-29 06:37:52 +0000 | [diff] [blame] | 774 | self.queue = deque() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 775 | |
| 776 | def put(self, item): |
| 777 | self.mon.acquire() |
| 778 | while len(self.queue) >= self.limit: |
| 779 | self._note("put(%s): queue full", item) |
| 780 | self.wc.wait() |
| 781 | self.queue.append(item) |
| 782 | self._note("put(%s): appended, length now %d", |
| 783 | item, len(self.queue)) |
| 784 | self.rc.notify() |
| 785 | self.mon.release() |
| 786 | |
| 787 | def get(self): |
| 788 | self.mon.acquire() |
| 789 | while not self.queue: |
| 790 | self._note("get(): queue empty") |
| 791 | self.rc.wait() |
Raymond Hettinger | 756b3f3 | 2004-01-29 06:37:52 +0000 | [diff] [blame] | 792 | item = self.queue.popleft() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 793 | self._note("get(): got %s, %d left", item, len(self.queue)) |
| 794 | self.wc.notify() |
| 795 | self.mon.release() |
| 796 | return item |
| 797 | |
| 798 | class ProducerThread(Thread): |
| 799 | |
| 800 | def __init__(self, queue, quota): |
| 801 | Thread.__init__(self, name="Producer") |
| 802 | self.queue = queue |
| 803 | self.quota = quota |
| 804 | |
| 805 | def run(self): |
Guido van Rossum | b26a1b4 | 1998-05-20 17:05:52 +0000 | [diff] [blame] | 806 | from random import random |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 807 | counter = 0 |
| 808 | while counter < self.quota: |
| 809 | counter = counter + 1 |
| 810 | self.queue.put("%s.%d" % (self.getName(), counter)) |
| 811 | _sleep(random() * 0.00001) |
| 812 | |
| 813 | |
| 814 | class ConsumerThread(Thread): |
| 815 | |
| 816 | def __init__(self, queue, count): |
| 817 | Thread.__init__(self, name="Consumer") |
| 818 | self.queue = queue |
| 819 | self.count = count |
| 820 | |
| 821 | def run(self): |
| 822 | while self.count > 0: |
| 823 | item = self.queue.get() |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 824 | print(item) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 825 | self.count = self.count - 1 |
| 826 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 827 | NP = 3 |
| 828 | QL = 4 |
| 829 | NI = 5 |
| 830 | |
| 831 | Q = BoundedQueue(QL) |
| 832 | P = [] |
| 833 | for i in range(NP): |
| 834 | t = ProducerThread(Q, NI) |
| 835 | t.setName("Producer-%d" % (i+1)) |
| 836 | P.append(t) |
| 837 | C = ConsumerThread(Q, NI*NP) |
| 838 | for t in P: |
| 839 | t.start() |
| 840 | _sleep(0.000001) |
| 841 | C.start() |
| 842 | for t in P: |
| 843 | t.join() |
| 844 | C.join() |
| 845 | |
| 846 | if __name__ == '__main__': |
| 847 | _test() |