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 | |
| 3 | import sys |
| 4 | import time |
| 5 | import thread |
| 6 | import traceback |
| 7 | import StringIO |
| 8 | |
| 9 | # Rename some stuff so "from threading import *" is safe |
| 10 | |
| 11 | _sys = sys |
| 12 | del sys |
| 13 | |
| 14 | _time = time.time |
| 15 | _sleep = time.sleep |
| 16 | del time |
| 17 | |
| 18 | _start_new_thread = thread.start_new_thread |
| 19 | _allocate_lock = thread.allocate_lock |
| 20 | _get_ident = thread.get_ident |
Jeremy Hylton | b5fc749 | 2000-06-01 01:17:17 +0000 | [diff] [blame] | 21 | ThreadError = thread.error |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 22 | del thread |
| 23 | |
| 24 | _print_exc = traceback.print_exc |
| 25 | del traceback |
| 26 | |
| 27 | _StringIO = StringIO.StringIO |
| 28 | del StringIO |
| 29 | |
| 30 | |
| 31 | # Debug support (adapted from ihooks.py) |
| 32 | |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 33 | _VERBOSE = 0 # XXX Bool or int? |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 34 | |
| 35 | if __debug__: |
| 36 | |
| 37 | class _Verbose: |
| 38 | |
| 39 | def __init__(self, verbose=None): |
| 40 | if verbose is None: |
| 41 | verbose = _VERBOSE |
| 42 | self.__verbose = verbose |
| 43 | |
| 44 | def _note(self, format, *args): |
| 45 | if self.__verbose: |
| 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" |
| 53 | class _Verbose: |
| 54 | def __init__(self, verbose=None): |
| 55 | pass |
| 56 | def _note(self, *args): |
| 57 | pass |
| 58 | |
| 59 | |
| 60 | # Synchronization classes |
| 61 | |
| 62 | Lock = _allocate_lock |
| 63 | |
| 64 | def RLock(*args, **kwargs): |
| 65 | return apply(_RLock, args, kwargs) |
| 66 | |
| 67 | class _RLock(_Verbose): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 68 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 69 | def __init__(self, verbose=None): |
| 70 | _Verbose.__init__(self, verbose) |
| 71 | self.__block = _allocate_lock() |
| 72 | self.__owner = None |
| 73 | self.__count = 0 |
| 74 | |
| 75 | def __repr__(self): |
| 76 | return "<%s(%s, %d)>" % ( |
| 77 | self.__class__.__name__, |
| 78 | self.__owner and self.__owner.getName(), |
| 79 | self.__count) |
| 80 | |
| 81 | def acquire(self, blocking=1): |
| 82 | me = currentThread() |
| 83 | if self.__owner is me: |
| 84 | self.__count = self.__count + 1 |
| 85 | if __debug__: |
| 86 | self._note("%s.acquire(%s): recursive success", self, blocking) |
| 87 | return 1 |
| 88 | rc = self.__block.acquire(blocking) |
| 89 | if rc: |
| 90 | self.__owner = me |
| 91 | self.__count = 1 |
| 92 | if __debug__: |
| 93 | self._note("%s.acquire(%s): initial succes", self, blocking) |
| 94 | else: |
| 95 | if __debug__: |
| 96 | self._note("%s.acquire(%s): failure", self, blocking) |
| 97 | return rc |
| 98 | |
| 99 | def release(self): |
| 100 | me = currentThread() |
| 101 | assert self.__owner is me, "release() of un-acquire()d lock" |
| 102 | self.__count = count = self.__count - 1 |
| 103 | if not count: |
| 104 | self.__owner = None |
| 105 | self.__block.release() |
| 106 | if __debug__: |
| 107 | self._note("%s.release(): final release", self) |
| 108 | else: |
| 109 | if __debug__: |
| 110 | self._note("%s.release(): non-final release", self) |
| 111 | |
| 112 | # Internal methods used by condition variables |
| 113 | |
| 114 | def _acquire_restore(self, (count, owner)): |
| 115 | self.__block.acquire() |
| 116 | self.__count = count |
| 117 | self.__owner = owner |
| 118 | if __debug__: |
| 119 | self._note("%s._acquire_restore()", self) |
| 120 | |
| 121 | def _release_save(self): |
| 122 | if __debug__: |
| 123 | self._note("%s._release_save()", self) |
| 124 | count = self.__count |
| 125 | self.__count = 0 |
| 126 | owner = self.__owner |
| 127 | self.__owner = None |
| 128 | self.__block.release() |
| 129 | return (count, owner) |
| 130 | |
| 131 | def _is_owned(self): |
| 132 | return self.__owner is currentThread() |
| 133 | |
| 134 | |
| 135 | def Condition(*args, **kwargs): |
| 136 | return apply(_Condition, args, kwargs) |
| 137 | |
| 138 | class _Condition(_Verbose): |
| 139 | |
| 140 | def __init__(self, lock=None, verbose=None): |
| 141 | _Verbose.__init__(self, verbose) |
| 142 | if lock is None: |
| 143 | lock = RLock() |
| 144 | self.__lock = lock |
| 145 | # Export the lock's acquire() and release() methods |
| 146 | self.acquire = lock.acquire |
| 147 | self.release = lock.release |
| 148 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 149 | # these override the default implementations (which just call |
| 150 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 151 | try: |
| 152 | self._release_save = lock._release_save |
| 153 | except AttributeError: |
| 154 | pass |
| 155 | try: |
| 156 | self._acquire_restore = lock._acquire_restore |
| 157 | except AttributeError: |
| 158 | pass |
| 159 | try: |
| 160 | self._is_owned = lock._is_owned |
| 161 | except AttributeError: |
| 162 | pass |
| 163 | self.__waiters = [] |
| 164 | |
| 165 | def __repr__(self): |
| 166 | return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters)) |
| 167 | |
| 168 | def _release_save(self): |
| 169 | self.__lock.release() # No state to save |
| 170 | |
| 171 | def _acquire_restore(self, x): |
| 172 | self.__lock.acquire() # Ignore saved state |
| 173 | |
| 174 | def _is_owned(self): |
Jeremy Hylton | 39c12bf | 2002-08-14 17:46:40 +0000 | [diff] [blame] | 175 | # Return True if lock is owned by currentThread. |
Jeremy Hylton | af7fde7 | 2002-08-14 17:43:59 +0000 | [diff] [blame] | 176 | # This method is called only if __lock doesn't have _is_owned(). |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 177 | if self.__lock.acquire(0): |
| 178 | self.__lock.release() |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 179 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 180 | else: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 181 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 182 | |
| 183 | def wait(self, timeout=None): |
Jeremy Hylton | 29c2106 | 2002-08-14 17:56:13 +0000 | [diff] [blame] | 184 | currentThread() # for side-effect |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 185 | assert self._is_owned(), "wait() of un-acquire()d lock" |
| 186 | waiter = _allocate_lock() |
| 187 | waiter.acquire() |
| 188 | self.__waiters.append(waiter) |
| 189 | saved_state = self._release_save() |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 190 | try: # restore state no matter what (e.g., KeyboardInterrupt) |
| 191 | if timeout is None: |
| 192 | waiter.acquire() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 193 | if __debug__: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 194 | self._note("%s.wait(): got it", self) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 195 | else: |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 196 | # Balancing act: We can't afford a pure busy loop, so we |
| 197 | # have to sleep; but if we sleep the whole timeout time, |
| 198 | # we'll be unresponsive. The scheme here sleeps very |
| 199 | # little at first, longer as time goes on, but never longer |
| 200 | # than 20 times per second (or the timeout time remaining). |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 201 | endtime = _time() + timeout |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 202 | delay = 0.0005 # 500 us -> initial delay of 1 ms |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 203 | while True: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 204 | gotit = waiter.acquire(0) |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 205 | if gotit: |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 206 | break |
Tim Peters | a6a4f27 | 2001-08-12 00:41:33 +0000 | [diff] [blame] | 207 | remaining = endtime - _time() |
| 208 | if remaining <= 0: |
| 209 | break |
| 210 | delay = min(delay * 2, remaining, .05) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 211 | _sleep(delay) |
Tim Peters | c951bf9 | 2001-04-02 20:15:57 +0000 | [diff] [blame] | 212 | if not gotit: |
| 213 | if __debug__: |
| 214 | self._note("%s.wait(%s): timed out", self, timeout) |
| 215 | try: |
| 216 | self.__waiters.remove(waiter) |
| 217 | except ValueError: |
| 218 | pass |
| 219 | else: |
| 220 | if __debug__: |
| 221 | self._note("%s.wait(%s): got it", self, timeout) |
| 222 | finally: |
| 223 | self._acquire_restore(saved_state) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 224 | |
| 225 | def notify(self, n=1): |
Jeremy Hylton | 29c2106 | 2002-08-14 17:56:13 +0000 | [diff] [blame] | 226 | currentThread() # for side-effect |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 227 | assert self._is_owned(), "notify() of un-acquire()d lock" |
| 228 | __waiters = self.__waiters |
| 229 | waiters = __waiters[:n] |
| 230 | if not waiters: |
| 231 | if __debug__: |
| 232 | self._note("%s.notify(): no waiters", self) |
| 233 | return |
| 234 | self._note("%s.notify(): notifying %d waiter%s", self, n, |
| 235 | n!=1 and "s" or "") |
| 236 | for waiter in waiters: |
| 237 | waiter.release() |
| 238 | try: |
| 239 | __waiters.remove(waiter) |
| 240 | except ValueError: |
| 241 | pass |
| 242 | |
| 243 | def notifyAll(self): |
| 244 | self.notify(len(self.__waiters)) |
| 245 | |
| 246 | |
| 247 | def Semaphore(*args, **kwargs): |
| 248 | return apply(_Semaphore, args, kwargs) |
| 249 | |
| 250 | class _Semaphore(_Verbose): |
| 251 | |
Andrew M. Kuchling | 39d3bfc | 2000-02-29 00:10:24 +0000 | [diff] [blame] | 252 | # 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] | 253 | |
| 254 | def __init__(self, value=1, verbose=None): |
| 255 | assert value >= 0, "Semaphore initial value must be >= 0" |
| 256 | _Verbose.__init__(self, verbose) |
| 257 | self.__cond = Condition(Lock()) |
| 258 | self.__value = value |
| 259 | |
| 260 | def acquire(self, blocking=1): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 261 | rc = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 262 | self.__cond.acquire() |
| 263 | while self.__value == 0: |
| 264 | if not blocking: |
| 265 | break |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 266 | if __debug__: |
| 267 | self._note("%s.acquire(%s): blocked waiting, value=%s", |
| 268 | self, blocking, self.__value) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 269 | self.__cond.wait() |
| 270 | else: |
| 271 | self.__value = self.__value - 1 |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 272 | if __debug__: |
Skip Montanaro | ae8454a | 2001-08-19 05:53:47 +0000 | [diff] [blame] | 273 | self._note("%s.acquire: success, value=%s", |
| 274 | self, self.__value) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 275 | rc = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 276 | self.__cond.release() |
| 277 | return rc |
| 278 | |
| 279 | def release(self): |
| 280 | self.__cond.acquire() |
| 281 | self.__value = self.__value + 1 |
Skip Montanaro | b446fc7 | 2001-08-19 04:25:24 +0000 | [diff] [blame] | 282 | if __debug__: |
Skip Montanaro | ae8454a | 2001-08-19 05:53:47 +0000 | [diff] [blame] | 283 | self._note("%s.release: success, value=%s", |
| 284 | self, self.__value) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 285 | self.__cond.notify() |
| 286 | self.__cond.release() |
| 287 | |
| 288 | |
Skip Montanaro | e428bb7 | 2001-08-20 20:27:58 +0000 | [diff] [blame] | 289 | def BoundedSemaphore(*args, **kwargs): |
| 290 | return apply(_BoundedSemaphore, args, kwargs) |
| 291 | |
| 292 | class _BoundedSemaphore(_Semaphore): |
| 293 | """Semaphore that checks that # releases is <= # acquires""" |
| 294 | def __init__(self, value=1, verbose=None): |
| 295 | _Semaphore.__init__(self, value, verbose) |
| 296 | self._initial_value = value |
| 297 | |
| 298 | def release(self): |
| 299 | if self._Semaphore__value >= self._initial_value: |
| 300 | raise ValueError, "Semaphore released too many times" |
| 301 | return _Semaphore.release(self) |
| 302 | |
| 303 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 304 | def Event(*args, **kwargs): |
| 305 | return apply(_Event, args, kwargs) |
| 306 | |
| 307 | class _Event(_Verbose): |
| 308 | |
| 309 | # After Tim Peters' event class (without is_posted()) |
| 310 | |
| 311 | def __init__(self, verbose=None): |
| 312 | _Verbose.__init__(self, verbose) |
| 313 | self.__cond = Condition(Lock()) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 314 | self.__flag = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 315 | |
| 316 | def isSet(self): |
| 317 | return self.__flag |
| 318 | |
| 319 | def set(self): |
| 320 | self.__cond.acquire() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 321 | try: |
| 322 | self.__flag = True |
| 323 | self.__cond.notifyAll() |
| 324 | finally: |
| 325 | self.__cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 326 | |
| 327 | def clear(self): |
| 328 | self.__cond.acquire() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 329 | try: |
| 330 | self.__flag = False |
| 331 | finally: |
| 332 | self.__cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 333 | |
| 334 | def wait(self, timeout=None): |
| 335 | self.__cond.acquire() |
Guido van Rossum | 21b6014 | 2002-11-21 21:08:39 +0000 | [diff] [blame] | 336 | try: |
| 337 | if not self.__flag: |
| 338 | self.__cond.wait(timeout) |
| 339 | finally: |
| 340 | self.__cond.release() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 341 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 342 | # Helper to generate new thread names |
| 343 | _counter = 0 |
| 344 | def _newname(template="Thread-%d"): |
| 345 | global _counter |
| 346 | _counter = _counter + 1 |
| 347 | return template % _counter |
| 348 | |
| 349 | # Active thread administration |
| 350 | _active_limbo_lock = _allocate_lock() |
| 351 | _active = {} |
| 352 | _limbo = {} |
| 353 | |
| 354 | |
| 355 | # Main class for threads |
| 356 | |
| 357 | class Thread(_Verbose): |
| 358 | |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 359 | __initialized = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 360 | |
| 361 | def __init__(self, group=None, target=None, name=None, |
| 362 | args=(), kwargs={}, verbose=None): |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 363 | assert group is None, "group argument must be None for now" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 364 | _Verbose.__init__(self, verbose) |
| 365 | self.__target = target |
| 366 | self.__name = str(name or _newname()) |
| 367 | self.__args = args |
| 368 | self.__kwargs = kwargs |
| 369 | self.__daemonic = self._set_daemon() |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 370 | self.__started = False |
| 371 | self.__stopped = False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 372 | self.__block = Condition(Lock()) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 373 | self.__initialized = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 374 | |
| 375 | def _set_daemon(self): |
| 376 | # Overridden in _MainThread and _DummyThread |
| 377 | return currentThread().isDaemon() |
| 378 | |
| 379 | def __repr__(self): |
| 380 | assert self.__initialized, "Thread.__init__() was not called" |
| 381 | status = "initial" |
| 382 | if self.__started: |
| 383 | status = "started" |
| 384 | if self.__stopped: |
| 385 | status = "stopped" |
| 386 | if self.__daemonic: |
| 387 | status = status + " daemon" |
| 388 | return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status) |
| 389 | |
| 390 | def start(self): |
| 391 | assert self.__initialized, "Thread.__init__() not called" |
| 392 | assert not self.__started, "thread already started" |
| 393 | if __debug__: |
| 394 | self._note("%s.start(): starting thread", self) |
| 395 | _active_limbo_lock.acquire() |
| 396 | _limbo[self] = self |
| 397 | _active_limbo_lock.release() |
| 398 | _start_new_thread(self.__bootstrap, ()) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 399 | self.__started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 400 | _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack) |
| 401 | |
| 402 | def run(self): |
| 403 | if self.__target: |
| 404 | apply(self.__target, self.__args, self.__kwargs) |
| 405 | |
| 406 | def __bootstrap(self): |
| 407 | try: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 408 | self.__started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 409 | _active_limbo_lock.acquire() |
| 410 | _active[_get_ident()] = self |
| 411 | del _limbo[self] |
| 412 | _active_limbo_lock.release() |
| 413 | if __debug__: |
| 414 | self._note("%s.__bootstrap(): thread started", self) |
| 415 | try: |
| 416 | self.run() |
| 417 | except SystemExit: |
| 418 | if __debug__: |
| 419 | self._note("%s.__bootstrap(): raised SystemExit", self) |
| 420 | except: |
| 421 | if __debug__: |
| 422 | self._note("%s.__bootstrap(): unhandled exception", self) |
| 423 | s = _StringIO() |
| 424 | _print_exc(file=s) |
| 425 | _sys.stderr.write("Exception in thread %s:\n%s\n" % |
| 426 | (self.getName(), s.getvalue())) |
| 427 | else: |
| 428 | if __debug__: |
| 429 | self._note("%s.__bootstrap(): normal return", self) |
| 430 | finally: |
| 431 | self.__stop() |
Guido van Rossum | f21b2aa | 2001-12-28 22:07:09 +0000 | [diff] [blame] | 432 | try: |
| 433 | self.__delete() |
| 434 | except: |
| 435 | pass |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 436 | |
| 437 | def __stop(self): |
| 438 | self.__block.acquire() |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 439 | self.__stopped = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 440 | self.__block.notifyAll() |
| 441 | self.__block.release() |
| 442 | |
| 443 | def __delete(self): |
| 444 | _active_limbo_lock.acquire() |
| 445 | del _active[_get_ident()] |
| 446 | _active_limbo_lock.release() |
| 447 | |
| 448 | def join(self, timeout=None): |
| 449 | assert self.__initialized, "Thread.__init__() not called" |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 450 | assert self.__started, "cannot join thread before it is started" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 451 | assert self is not currentThread(), "cannot join current thread" |
| 452 | if __debug__: |
| 453 | if not self.__stopped: |
| 454 | self._note("%s.join(): waiting until thread stops", self) |
| 455 | self.__block.acquire() |
| 456 | if timeout is None: |
Guido van Rossum | 5a43e1a | 1998-06-09 19:04:26 +0000 | [diff] [blame] | 457 | while not self.__stopped: |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 458 | self.__block.wait() |
| 459 | if __debug__: |
| 460 | self._note("%s.join(): thread stopped", self) |
| 461 | else: |
Guido van Rossum | b39e461 | 1998-05-29 17:47:10 +0000 | [diff] [blame] | 462 | deadline = _time() + timeout |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 463 | while not self.__stopped: |
Guido van Rossum | b39e461 | 1998-05-29 17:47:10 +0000 | [diff] [blame] | 464 | delay = deadline - _time() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 465 | if delay <= 0: |
| 466 | if __debug__: |
| 467 | self._note("%s.join(): timed out", self) |
| 468 | break |
| 469 | self.__block.wait(delay) |
| 470 | else: |
| 471 | if __debug__: |
| 472 | self._note("%s.join(): thread stopped", self) |
| 473 | self.__block.release() |
| 474 | |
| 475 | def getName(self): |
| 476 | assert self.__initialized, "Thread.__init__() not called" |
| 477 | return self.__name |
| 478 | |
| 479 | def setName(self, name): |
| 480 | assert self.__initialized, "Thread.__init__() not called" |
| 481 | self.__name = str(name) |
| 482 | |
| 483 | def isAlive(self): |
| 484 | assert self.__initialized, "Thread.__init__() not called" |
| 485 | return self.__started and not self.__stopped |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 486 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 487 | def isDaemon(self): |
| 488 | assert self.__initialized, "Thread.__init__() not called" |
| 489 | return self.__daemonic |
| 490 | |
| 491 | def setDaemon(self, daemonic): |
| 492 | assert self.__initialized, "Thread.__init__() not called" |
| 493 | assert not self.__started, "cannot set daemon status of active thread" |
| 494 | self.__daemonic = daemonic |
| 495 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 496 | # The timer class was contributed by Itamar Shtull-Trauring |
| 497 | |
| 498 | def Timer(*args, **kwargs): |
| 499 | return _Timer(*args, **kwargs) |
| 500 | |
| 501 | class _Timer(Thread): |
| 502 | """Call a function after a specified number of seconds: |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 503 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 504 | t = Timer(30.0, f, args=[], kwargs={}) |
| 505 | t.start() |
| 506 | t.cancel() # stop the timer's action if it's still waiting |
| 507 | """ |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 508 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 509 | def __init__(self, interval, function, args=[], kwargs={}): |
| 510 | Thread.__init__(self) |
| 511 | self.interval = interval |
| 512 | self.function = function |
| 513 | self.args = args |
| 514 | self.kwargs = kwargs |
| 515 | self.finished = Event() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 516 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 517 | def cancel(self): |
| 518 | """Stop the timer if it hasn't finished yet""" |
| 519 | self.finished.set() |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 520 | |
Martin v. Löwis | 44f8696 | 2001-09-05 13:44:54 +0000 | [diff] [blame] | 521 | def run(self): |
| 522 | self.finished.wait(self.interval) |
| 523 | if not self.finished.isSet(): |
| 524 | self.function(*self.args, **self.kwargs) |
| 525 | self.finished.set() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 526 | |
| 527 | # Special thread class to represent the main thread |
| 528 | # This is garbage collected through an exit handler |
| 529 | |
| 530 | class _MainThread(Thread): |
| 531 | |
| 532 | def __init__(self): |
| 533 | Thread.__init__(self, name="MainThread") |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 534 | self._Thread__started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 535 | _active_limbo_lock.acquire() |
| 536 | _active[_get_ident()] = self |
| 537 | _active_limbo_lock.release() |
Fred Drake | 7b4fc17 | 2000-08-18 15:50:54 +0000 | [diff] [blame] | 538 | import atexit |
| 539 | atexit.register(self.__exitfunc) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 540 | |
| 541 | def _set_daemon(self): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 542 | return False |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 543 | |
| 544 | def __exitfunc(self): |
| 545 | self._Thread__stop() |
| 546 | t = _pickSomeNonDaemonThread() |
| 547 | if t: |
| 548 | if __debug__: |
| 549 | self._note("%s: waiting for other threads", self) |
| 550 | while t: |
| 551 | t.join() |
| 552 | t = _pickSomeNonDaemonThread() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 553 | if __debug__: |
| 554 | self._note("%s: exiting", self) |
| 555 | self._Thread__delete() |
| 556 | |
| 557 | def _pickSomeNonDaemonThread(): |
| 558 | for t in enumerate(): |
| 559 | if not t.isDaemon() and t.isAlive(): |
| 560 | return t |
| 561 | return None |
| 562 | |
| 563 | |
| 564 | # Dummy thread class to represent threads not started here. |
| 565 | # These aren't garbage collected when they die, |
| 566 | # nor can they be waited for. |
| 567 | # Their purpose is to return *something* from currentThread(). |
| 568 | # They are marked as daemon threads so we won't wait for them |
| 569 | # when we exit (conform previous semantics). |
| 570 | |
| 571 | class _DummyThread(Thread): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 572 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 573 | def __init__(self): |
| 574 | Thread.__init__(self, name=_newname("Dummy-%d")) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 575 | self._Thread__started = True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 576 | _active_limbo_lock.acquire() |
| 577 | _active[_get_ident()] = self |
| 578 | _active_limbo_lock.release() |
| 579 | |
| 580 | def _set_daemon(self): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 581 | return True |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 582 | |
Neal Norwitz | 45bec8c | 2002-02-19 03:01:36 +0000 | [diff] [blame] | 583 | def join(self, timeout=None): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 584 | assert False, "cannot join a dummy thread" |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 585 | |
| 586 | |
| 587 | # Global API functions |
| 588 | |
| 589 | def currentThread(): |
| 590 | try: |
| 591 | return _active[_get_ident()] |
| 592 | except KeyError: |
Guido van Rossum | 5080b33 | 2000-12-15 20:08:39 +0000 | [diff] [blame] | 593 | ##print "currentThread(): no current thread for", _get_ident() |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 594 | return _DummyThread() |
| 595 | |
| 596 | def activeCount(): |
| 597 | _active_limbo_lock.acquire() |
| 598 | count = len(_active) + len(_limbo) |
| 599 | _active_limbo_lock.release() |
| 600 | return count |
| 601 | |
| 602 | def enumerate(): |
| 603 | _active_limbo_lock.acquire() |
| 604 | active = _active.values() + _limbo.values() |
| 605 | _active_limbo_lock.release() |
| 606 | return active |
| 607 | |
| 608 | |
| 609 | # Create the main thread object |
| 610 | |
| 611 | _MainThread() |
| 612 | |
| 613 | |
| 614 | # Self-test code |
| 615 | |
| 616 | def _test(): |
| 617 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 618 | class BoundedQueue(_Verbose): |
| 619 | |
| 620 | def __init__(self, limit): |
| 621 | _Verbose.__init__(self) |
| 622 | self.mon = RLock() |
| 623 | self.rc = Condition(self.mon) |
| 624 | self.wc = Condition(self.mon) |
| 625 | self.limit = limit |
| 626 | self.queue = [] |
| 627 | |
| 628 | def put(self, item): |
| 629 | self.mon.acquire() |
| 630 | while len(self.queue) >= self.limit: |
| 631 | self._note("put(%s): queue full", item) |
| 632 | self.wc.wait() |
| 633 | self.queue.append(item) |
| 634 | self._note("put(%s): appended, length now %d", |
| 635 | item, len(self.queue)) |
| 636 | self.rc.notify() |
| 637 | self.mon.release() |
| 638 | |
| 639 | def get(self): |
| 640 | self.mon.acquire() |
| 641 | while not self.queue: |
| 642 | self._note("get(): queue empty") |
| 643 | self.rc.wait() |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 644 | item = self.queue.pop(0) |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 645 | self._note("get(): got %s, %d left", item, len(self.queue)) |
| 646 | self.wc.notify() |
| 647 | self.mon.release() |
| 648 | return item |
| 649 | |
| 650 | class ProducerThread(Thread): |
| 651 | |
| 652 | def __init__(self, queue, quota): |
| 653 | Thread.__init__(self, name="Producer") |
| 654 | self.queue = queue |
| 655 | self.quota = quota |
| 656 | |
| 657 | def run(self): |
Guido van Rossum | b26a1b4 | 1998-05-20 17:05:52 +0000 | [diff] [blame] | 658 | from random import random |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 659 | counter = 0 |
| 660 | while counter < self.quota: |
| 661 | counter = counter + 1 |
| 662 | self.queue.put("%s.%d" % (self.getName(), counter)) |
| 663 | _sleep(random() * 0.00001) |
| 664 | |
| 665 | |
| 666 | class ConsumerThread(Thread): |
| 667 | |
| 668 | def __init__(self, queue, count): |
| 669 | Thread.__init__(self, name="Consumer") |
| 670 | self.queue = queue |
| 671 | self.count = count |
| 672 | |
| 673 | def run(self): |
| 674 | while self.count > 0: |
| 675 | item = self.queue.get() |
| 676 | print item |
| 677 | self.count = self.count - 1 |
| 678 | |
Guido van Rossum | 7f5013a | 1998-04-09 22:01:42 +0000 | [diff] [blame] | 679 | NP = 3 |
| 680 | QL = 4 |
| 681 | NI = 5 |
| 682 | |
| 683 | Q = BoundedQueue(QL) |
| 684 | P = [] |
| 685 | for i in range(NP): |
| 686 | t = ProducerThread(Q, NI) |
| 687 | t.setName("Producer-%d" % (i+1)) |
| 688 | P.append(t) |
| 689 | C = ConsumerThread(Q, NI*NP) |
| 690 | for t in P: |
| 691 | t.start() |
| 692 | _sleep(0.000001) |
| 693 | C.start() |
| 694 | for t in P: |
| 695 | t.join() |
| 696 | C.join() |
| 697 | |
| 698 | if __name__ == '__main__': |
| 699 | _test() |