1 """Thread module emulating a subset of Java's threading model."""
3 # This started life as the threading.py module of Python 2.3
4 # It's been patched to fix a problem with join, where a KeyboardInterrupt
5 # caused a lock to be left in the acquired state.
12 del _sys.modules[__name__]
15 from StringIO import StringIO as _StringIO
16 from time import time as _time, sleep as _sleep
17 from traceback import print_exc as _print_exc
19 # Rename some stuff so "from threading import *" is safe
20 __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event',
21 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
22 'Timer', 'setprofile', 'settrace']
24 _start_new_thread = thread.start_new_thread
25 _allocate_lock = thread.allocate_lock
26 _get_ident = thread.get_ident
27 ThreadError = thread.error
31 # Debug support (adapted from ihooks.py).
32 # All the major classes here derive from _Verbose. We force that to
33 # be a new-style class so that all the major classes here are new-style.
34 # This helps debugging (type(instance) is more revealing for instances
35 # of new-style classes).
41 class _Verbose(object):
43 def __init__(self, verbose=None):
46 self.__verbose = verbose
48 def _note(self, format, *args):
50 format = format % args
51 format = "%s: %s\n" % (
52 currentThread().getName(), format)
53 _sys.stderr.write(format)
56 # Disable this when using "python -O"
57 class _Verbose(object):
58 def __init__(self, verbose=None):
60 def _note(self, *args):
63 # Support for profile and trace hooks
76 # Synchronization classes
80 def RLock(*args, **kwargs):
81 return _RLock(*args, **kwargs)
83 class _RLock(_Verbose):
85 def __init__(self, verbose=None):
86 _Verbose.__init__(self, verbose)
87 self.__block = _allocate_lock()
92 return "<%s(%s, %d)>" % (
93 self.__class__.__name__,
94 self.__owner and self.__owner.getName(),
97 def acquire(self, blocking=1):
99 if self.__owner is me:
100 self.__count = self.__count + 1
102 self._note("%s.acquire(%s): recursive success", self, blocking)
104 rc = self.__block.acquire(blocking)
109 self._note("%s.acquire(%s): initial succes", self, blocking)
112 self._note("%s.acquire(%s): failure", self, blocking)
117 assert self.__owner is me, "release() of un-acquire()d lock"
118 self.__count = count = self.__count - 1
121 self.__block.release()
123 self._note("%s.release(): final release", self)
126 self._note("%s.release(): non-final release", self)
128 # Internal methods used by condition variables
130 def _acquire_restore(self, (count, owner)):
131 self.__block.acquire()
135 self._note("%s._acquire_restore()", self)
137 def _release_save(self):
139 self._note("%s._release_save()", self)
144 self.__block.release()
145 return (count, owner)
148 return self.__owner is currentThread()
151 def Condition(*args, **kwargs):
152 return _Condition(*args, **kwargs)
154 class _Condition(_Verbose):
156 def __init__(self, lock=None, verbose=None):
157 _Verbose.__init__(self, verbose)
161 # Export the lock's acquire() and release() methods
162 self.acquire = lock.acquire
163 self.release = lock.release
164 # If the lock defines _release_save() and/or _acquire_restore(),
165 # these override the default implementations (which just call
166 # release() and acquire() on the lock). Ditto for _is_owned().
168 self._release_save = lock._release_save
169 except AttributeError:
172 self._acquire_restore = lock._acquire_restore
173 except AttributeError:
176 self._is_owned = lock._is_owned
177 except AttributeError:
182 return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
184 def _release_save(self):
185 self.__lock.release() # No state to save
187 def _acquire_restore(self, x):
188 self.__lock.acquire() # Ignore saved state
191 # Return True if lock is owned by currentThread.
192 # This method is called only if __lock doesn't have _is_owned().
193 if self.__lock.acquire(0):
194 self.__lock.release()
199 def wait(self, timeout=None):
200 currentThread() # for side-effect
201 assert self._is_owned(), "wait() of un-acquire()d lock"
202 waiter = _allocate_lock()
204 self.__waiters.append(waiter)
205 saved_state = self._release_save()
206 try: # restore state no matter what (e.g., KeyboardInterrupt)
210 self._note("%s.wait(): got it", self)
212 # Balancing act: We can't afford a pure busy loop, so we
213 # have to sleep; but if we sleep the whole timeout time,
214 # we'll be unresponsive. The scheme here sleeps very
215 # little at first, longer as time goes on, but never longer
216 # than 20 times per second (or the timeout time remaining).
217 endtime = _time() + timeout
218 delay = 0.0005 # 500 us -> initial delay of 1 ms
220 gotit = waiter.acquire(0)
223 remaining = endtime - _time()
226 delay = min(delay * 2, remaining, .05)
230 self._note("%s.wait(%s): timed out", self, timeout)
232 self.__waiters.remove(waiter)
237 self._note("%s.wait(%s): got it", self, timeout)
239 self._acquire_restore(saved_state)
241 def notify(self, n=1):
242 currentThread() # for side-effect
243 assert self._is_owned(), "notify() of un-acquire()d lock"
244 __waiters = self.__waiters
245 waiters = __waiters[:n]
248 self._note("%s.notify(): no waiters", self)
250 self._note("%s.notify(): notifying %d waiter%s", self, n,
252 for waiter in waiters:
255 __waiters.remove(waiter)
260 self.notify(len(self.__waiters))
263 def Semaphore(*args, **kwargs):
264 return _Semaphore(*args, **kwargs)
266 class _Semaphore(_Verbose):
268 # After Tim Peters' semaphore class, but not quite the same (no maximum)
270 def __init__(self, value=1, verbose=None):
271 assert value >= 0, "Semaphore initial value must be >= 0"
272 _Verbose.__init__(self, verbose)
273 self.__cond = Condition(Lock())
276 def acquire(self, blocking=1):
278 self.__cond.acquire()
279 while self.__value == 0:
283 self._note("%s.acquire(%s): blocked waiting, value=%s",
284 self, blocking, self.__value)
287 self.__value = self.__value - 1
289 self._note("%s.acquire: success, value=%s",
292 self.__cond.release()
296 self.__cond.acquire()
297 self.__value = self.__value + 1
299 self._note("%s.release: success, value=%s",
302 self.__cond.release()
305 def BoundedSemaphore(*args, **kwargs):
306 return _BoundedSemaphore(*args, **kwargs)
308 class _BoundedSemaphore(_Semaphore):
309 """Semaphore that checks that # releases is <= # acquires"""
310 def __init__(self, value=1, verbose=None):
311 _Semaphore.__init__(self, value, verbose)
312 self._initial_value = value
315 if self._Semaphore__value >= self._initial_value:
316 raise ValueError, "Semaphore released too many times"
317 return _Semaphore.release(self)
320 def Event(*args, **kwargs):
321 return _Event(*args, **kwargs)
323 class _Event(_Verbose):
325 # After Tim Peters' event class (without is_posted())
327 def __init__(self, verbose=None):
328 _Verbose.__init__(self, verbose)
329 self.__cond = Condition(Lock())
336 self.__cond.acquire()
339 self.__cond.notifyAll()
341 self.__cond.release()
344 self.__cond.acquire()
348 self.__cond.release()
350 def wait(self, timeout=None):
351 self.__cond.acquire()
354 self.__cond.wait(timeout)
356 self.__cond.release()
358 # Helper to generate new thread names
360 def _newname(template="Thread-%d"):
362 _counter = _counter + 1
363 return template % _counter
365 # Active thread administration
366 _active_limbo_lock = _allocate_lock()
371 # Main class for threads
373 class Thread(_Verbose):
375 __initialized = False
377 def __init__(self, group=None, target=None, name=None,
378 args=(), kwargs={}, verbose=None):
379 assert group is None, "group argument must be None for now"
380 _Verbose.__init__(self, verbose)
381 self.__target = target
382 self.__name = str(name or _newname())
384 self.__kwargs = kwargs
385 self.__daemonic = self._set_daemon()
386 self.__started = False
387 self.__stopped = False
388 self.__block = Condition(Lock())
389 self.__initialized = True
391 def _set_daemon(self):
392 # Overridden in _MainThread and _DummyThread
393 return currentThread().isDaemon()
396 assert self.__initialized, "Thread.__init__() was not called"
403 status = status + " daemon"
404 return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
407 assert self.__initialized, "Thread.__init__() not called"
408 assert not self.__started, "thread already started"
410 self._note("%s.start(): starting thread", self)
411 _active_limbo_lock.acquire()
413 _active_limbo_lock.release()
414 _start_new_thread(self.__bootstrap, ())
415 self.__started = True
416 _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
420 self.__target(*self.__args, **self.__kwargs)
422 def __bootstrap(self):
424 self.__started = True
425 _active_limbo_lock.acquire()
426 _active[_get_ident()] = self
428 _active_limbo_lock.release()
430 self._note("%s.__bootstrap(): thread started", self)
433 self._note("%s.__bootstrap(): registering trace hook", self)
434 _sys.settrace(_trace_hook)
436 self._note("%s.__bootstrap(): registering profile hook", self)
437 _sys.setprofile(_profile_hook)
443 self._note("%s.__bootstrap(): raised SystemExit", self)
446 self._note("%s.__bootstrap(): unhandled exception", self)
449 _sys.stderr.write("Exception in thread %s:\n%s\n" %
450 (self.getName(), s.getvalue()))
453 self._note("%s.__bootstrap(): normal return", self)
462 self.__block.acquire()
463 self.__stopped = True
464 self.__block.notifyAll()
465 self.__block.release()
468 _active_limbo_lock.acquire()
469 del _active[_get_ident()]
470 _active_limbo_lock.release()
472 def join(self, timeout=None):
473 assert self.__initialized, "Thread.__init__() not called"
474 assert self.__started, "cannot join thread before it is started"
475 assert self is not currentThread(), "cannot join current thread"
477 if not self.__stopped:
478 self._note("%s.join(): waiting until thread stops", self)
479 self.__block.acquire()
482 while not self.__stopped:
485 self._note("%s.join(): thread stopped", self)
487 deadline = _time() + timeout
488 while not self.__stopped:
489 delay = deadline - _time()
492 self._note("%s.join(): timed out", self)
494 self.__block.wait(delay)
497 self._note("%s.join(): thread stopped", self)
499 self.__block.release()
502 assert self.__initialized, "Thread.__init__() not called"
505 def setName(self, name):
506 assert self.__initialized, "Thread.__init__() not called"
507 self.__name = str(name)
510 assert self.__initialized, "Thread.__init__() not called"
511 return self.__started and not self.__stopped
514 assert self.__initialized, "Thread.__init__() not called"
515 return self.__daemonic
517 def setDaemon(self, daemonic):
518 assert self.__initialized, "Thread.__init__() not called"
519 assert not self.__started, "cannot set daemon status of active thread"
520 self.__daemonic = daemonic
522 # The timer class was contributed by Itamar Shtull-Trauring
524 def Timer(*args, **kwargs):
525 return _Timer(*args, **kwargs)
527 class _Timer(Thread):
528 """Call a function after a specified number of seconds:
530 t = Timer(30.0, f, args=[], kwargs={})
532 t.cancel() # stop the timer's action if it's still waiting
535 def __init__(self, interval, function, args=[], kwargs={}):
536 Thread.__init__(self)
537 self.interval = interval
538 self.function = function
541 self.finished = Event()
544 """Stop the timer if it hasn't finished yet"""
548 self.finished.wait(self.interval)
549 if not self.finished.isSet():
550 self.function(*self.args, **self.kwargs)
553 # Special thread class to represent the main thread
554 # This is garbage collected through an exit handler
556 class _MainThread(Thread):
559 Thread.__init__(self, name="MainThread")
560 self._Thread__started = True
561 _active_limbo_lock.acquire()
562 _active[_get_ident()] = self
563 _active_limbo_lock.release()
565 atexit.register(self.__exitfunc)
567 def _set_daemon(self):
570 def __exitfunc(self):
572 t = _pickSomeNonDaemonThread()
575 self._note("%s: waiting for other threads", self)
578 t = _pickSomeNonDaemonThread()
580 self._note("%s: exiting", self)
581 self._Thread__delete()
583 def _pickSomeNonDaemonThread():
584 for t in enumerate():
585 if not t.isDaemon() and t.isAlive():
590 # Dummy thread class to represent threads not started here.
591 # These aren't garbage collected when they die,
592 # nor can they be waited for.
593 # Their purpose is to return *something* from currentThread().
594 # They are marked as daemon threads so we won't wait for them
595 # when we exit (conform previous semantics).
597 class _DummyThread(Thread):
600 Thread.__init__(self, name=_newname("Dummy-%d"))
601 self._Thread__started = True
602 _active_limbo_lock.acquire()
603 _active[_get_ident()] = self
604 _active_limbo_lock.release()
606 def _set_daemon(self):
609 def join(self, timeout=None):
610 assert False, "cannot join a dummy thread"
613 # Global API functions
617 return _active[_get_ident()]
619 ##print "currentThread(): no current thread for", _get_ident()
620 return _DummyThread()
623 _active_limbo_lock.acquire()
624 count = len(_active) + len(_limbo)
625 _active_limbo_lock.release()
629 _active_limbo_lock.acquire()
630 active = _active.values() + _limbo.values()
631 _active_limbo_lock.release()
634 # Create the main thread object
643 class BoundedQueue(_Verbose):
645 def __init__(self, limit):
646 _Verbose.__init__(self)
648 self.rc = Condition(self.mon)
649 self.wc = Condition(self.mon)
655 while len(self.queue) >= self.limit:
656 self._note("put(%s): queue full", item)
658 self.queue.append(item)
659 self._note("put(%s): appended, length now %d",
660 item, len(self.queue))
666 while not self.queue:
667 self._note("get(): queue empty")
669 item = self.queue.pop(0)
670 self._note("get(): got %s, %d left", item, len(self.queue))
675 class ProducerThread(Thread):
677 def __init__(self, queue, quota):
678 Thread.__init__(self, name="Producer")
683 from random import random
685 while counter < self.quota:
686 counter = counter + 1
687 self.queue.put("%s.%d" % (self.getName(), counter))
688 _sleep(random() * 0.00001)
691 class ConsumerThread(Thread):
693 def __init__(self, queue, count):
694 Thread.__init__(self, name="Consumer")
699 while self.count > 0:
700 item = self.queue.get()
702 self.count = self.count - 1
711 t = ProducerThread(Q, NI)
712 t.setName("Producer-%d" % (i+1))
714 C = ConsumerThread(Q, NI*NP)
723 if __name__ == '__main__':