1 """Thread module emulating a subset of Java's threading model."""
8 del _sys
.modules
[__name__
]
11 from time
import time
as _time
, sleep
as _sleep
12 from traceback
import format_exc
as _format_exc
13 from collections
import deque
15 # Rename some stuff so "from threading import *" is safe
16 __all__
= ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event',
17 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
18 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
20 _start_new_thread
= thread
.start_new_thread
21 _allocate_lock
= thread
.allocate_lock
22 _get_ident
= thread
.get_ident
23 ThreadError
= thread
.error
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).
37 class _Verbose(object):
39 def __init__(self
, verbose
=None):
42 self
.__verbose
= verbose
44 def _note(self
, format
, *args
):
46 format
= format
% args
47 format
= "%s: %s\n" % (
48 currentThread().getName(), format
)
49 _sys
.stderr
.write(format
)
52 # Disable this when using "python -O"
53 class _Verbose(object):
54 def __init__(self
, verbose
=None):
56 def _note(self
, *args
):
59 # Support for profile and trace hooks
72 # Synchronization classes
76 def RLock(*args
, **kwargs
):
77 return _RLock(*args
, **kwargs
)
79 class _RLock(_Verbose
):
81 def __init__(self
, verbose
=None):
82 _Verbose
.__init
__(self
, verbose
)
83 self
.__block
= _allocate_lock()
89 return "<%s(%s, %d)>" % (
90 self
.__class
__.__name
__,
91 owner
and owner
.getName(),
94 def acquire(self
, blocking
=1):
96 if self
.__owner
is me
:
97 self
.__count
= self
.__count
+ 1
99 self
._note
("%s.acquire(%s): recursive success", self
, blocking
)
101 rc
= self
.__block
.acquire(blocking
)
106 self
._note
("%s.acquire(%s): initial success", self
, blocking
)
109 self
._note
("%s.acquire(%s): failure", self
, blocking
)
115 if self
.__owner
is not currentThread():
116 raise RuntimeError("cannot release un-aquired lock")
117 self
.__count
= count
= self
.__count
- 1
120 self
.__block
.release()
122 self
._note
("%s.release(): final release", self
)
125 self
._note
("%s.release(): non-final release", self
)
127 def __exit__(self
, t
, v
, tb
):
130 # Internal methods used by condition variables
132 def _acquire_restore(self
, (count
, owner
)):
133 self
.__block
.acquire()
137 self
._note
("%s._acquire_restore()", self
)
139 def _release_save(self
):
141 self
._note
("%s._release_save()", self
)
146 self
.__block
.release()
147 return (count
, owner
)
150 return self
.__owner
is currentThread()
153 def Condition(*args
, **kwargs
):
154 return _Condition(*args
, **kwargs
)
156 class _Condition(_Verbose
):
158 def __init__(self
, lock
=None, verbose
=None):
159 _Verbose
.__init
__(self
, verbose
)
163 # Export the lock's acquire() and release() methods
164 self
.acquire
= lock
.acquire
165 self
.release
= lock
.release
166 # If the lock defines _release_save() and/or _acquire_restore(),
167 # these override the default implementations (which just call
168 # release() and acquire() on the lock). Ditto for _is_owned().
170 self
._release
_save
= lock
._release
_save
171 except AttributeError:
174 self
._acquire
_restore
= lock
._acquire
_restore
175 except AttributeError:
178 self
._is
_owned
= lock
._is
_owned
179 except AttributeError:
184 return self
.__lock
.__enter
__()
186 def __exit__(self
, *args
):
187 return self
.__lock
.__exit
__(*args
)
190 return "<Condition(%s, %d)>" % (self
.__lock
, len(self
.__waiters
))
192 def _release_save(self
):
193 self
.__lock
.release() # No state to save
195 def _acquire_restore(self
, x
):
196 self
.__lock
.acquire() # Ignore saved state
199 # Return True if lock is owned by currentThread.
200 # This method is called only if __lock doesn't have _is_owned().
201 if self
.__lock
.acquire(0):
202 self
.__lock
.release()
207 def wait(self
, timeout
=None):
208 if not self
._is
_owned
():
209 raise RuntimeError("cannot wait on un-aquired lock")
210 waiter
= _allocate_lock()
212 self
.__waiters
.append(waiter
)
213 saved_state
= self
._release
_save
()
214 try: # restore state no matter what (e.g., KeyboardInterrupt)
218 self
._note
("%s.wait(): got it", self
)
220 # Balancing act: We can't afford a pure busy loop, so we
221 # have to sleep; but if we sleep the whole timeout time,
222 # we'll be unresponsive. The scheme here sleeps very
223 # little at first, longer as time goes on, but never longer
224 # than 20 times per second (or the timeout time remaining).
225 endtime
= _time() + timeout
226 delay
= 0.0005 # 500 us -> initial delay of 1 ms
228 gotit
= waiter
.acquire(0)
231 remaining
= endtime
- _time()
234 delay
= min(delay
* 2, remaining
, .05)
238 self
._note
("%s.wait(%s): timed out", self
, timeout
)
240 self
.__waiters
.remove(waiter
)
245 self
._note
("%s.wait(%s): got it", self
, timeout
)
247 self
._acquire
_restore
(saved_state
)
249 def notify(self
, n
=1):
250 if not self
._is
_owned
():
251 raise RuntimeError("cannot notify on un-aquired lock")
252 __waiters
= self
.__waiters
253 waiters
= __waiters
[:n
]
256 self
._note
("%s.notify(): no waiters", self
)
258 self
._note
("%s.notify(): notifying %d waiter%s", self
, n
,
260 for waiter
in waiters
:
263 __waiters
.remove(waiter
)
268 self
.notify(len(self
.__waiters
))
271 def Semaphore(*args
, **kwargs
):
272 return _Semaphore(*args
, **kwargs
)
274 class _Semaphore(_Verbose
):
276 # After Tim Peters' semaphore class, but not quite the same (no maximum)
278 def __init__(self
, value
=1, verbose
=None):
280 raise ValueError("semaphore initial value must be >= 0")
281 _Verbose
.__init
__(self
, verbose
)
282 self
.__cond
= Condition(Lock())
285 def acquire(self
, blocking
=1):
287 self
.__cond
.acquire()
288 while self
.__value
== 0:
292 self
._note
("%s.acquire(%s): blocked waiting, value=%s",
293 self
, blocking
, self
.__value
)
296 self
.__value
= self
.__value
- 1
298 self
._note
("%s.acquire: success, value=%s",
301 self
.__cond
.release()
307 self
.__cond
.acquire()
308 self
.__value
= self
.__value
+ 1
310 self
._note
("%s.release: success, value=%s",
313 self
.__cond
.release()
315 def __exit__(self
, t
, v
, tb
):
319 def BoundedSemaphore(*args
, **kwargs
):
320 return _BoundedSemaphore(*args
, **kwargs
)
322 class _BoundedSemaphore(_Semaphore
):
323 """Semaphore that checks that # releases is <= # acquires"""
324 def __init__(self
, value
=1, verbose
=None):
325 _Semaphore
.__init
__(self
, value
, verbose
)
326 self
._initial
_value
= value
329 if self
._Semaphore
__value
>= self
._initial
_value
:
330 raise ValueError, "Semaphore released too many times"
331 return _Semaphore
.release(self
)
334 def Event(*args
, **kwargs
):
335 return _Event(*args
, **kwargs
)
337 class _Event(_Verbose
):
339 # After Tim Peters' event class (without is_posted())
341 def __init__(self
, verbose
=None):
342 _Verbose
.__init
__(self
, verbose
)
343 self
.__cond
= Condition(Lock())
350 self
.__cond
.acquire()
353 self
.__cond
.notifyAll()
355 self
.__cond
.release()
358 self
.__cond
.acquire()
362 self
.__cond
.release()
364 def wait(self
, timeout
=None):
365 self
.__cond
.acquire()
368 self
.__cond
.wait(timeout
)
370 self
.__cond
.release()
372 # Helper to generate new thread names
374 def _newname(template
="Thread-%d"):
376 _counter
= _counter
+ 1
377 return template
% _counter
379 # Active thread administration
380 _active_limbo_lock
= _allocate_lock()
381 _active
= {} # maps thread id to Thread object
385 # Main class for threads
387 class Thread(_Verbose
):
389 __initialized
= False
390 # Need to store a reference to sys.exc_info for printing
391 # out exceptions when a thread tries to use a global var. during interp.
392 # shutdown and thus raises an exception about trying to perform some
393 # operation on/with a NoneType
394 __exc_info
= _sys
.exc_info
396 def __init__(self
, group
=None, target
=None, name
=None,
397 args
=(), kwargs
=None, verbose
=None):
398 assert group
is None, "group argument must be None for now"
399 _Verbose
.__init
__(self
, verbose
)
402 self
.__target
= target
403 self
.__name
= str(name
or _newname())
405 self
.__kwargs
= kwargs
406 self
.__daemonic
= self
._set
_daemon
()
407 self
.__started
= False
408 self
.__stopped
= False
409 self
.__block
= Condition(Lock())
410 self
.__initialized
= True
411 # sys.stderr is not stored in the class like
412 # sys.exc_info since it can be changed between instances
413 self
.__stderr
= _sys
.stderr
415 def _set_daemon(self
):
416 # Overridden in _MainThread and _DummyThread
417 return currentThread().isDaemon()
420 assert self
.__initialized
, "Thread.__init__() was not called"
427 status
= status
+ " daemon"
428 return "<%s(%s, %s)>" % (self
.__class
__.__name
__, self
.__name
, status
)
431 if not self
.__initialized
:
432 raise RuntimeError("thread.__init__() not called")
434 raise RuntimeError("thread already started")
436 self
._note
("%s.start(): starting thread", self
)
437 _active_limbo_lock
.acquire()
439 _active_limbo_lock
.release()
440 _start_new_thread(self
.__bootstrap
, ())
441 self
.__started
= True
442 _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
446 self
.__target
(*self
.__args
, **self
.__kwargs
)
448 def __bootstrap(self
):
449 # Wrapper around the real bootstrap code that ignores
450 # exceptions during interpreter cleanup. Those typically
451 # happen when a daemon thread wakes up at an unfortunate
452 # moment, finds the world around it destroyed, and raises some
453 # random exception *** while trying to report the exception in
454 # __bootstrap_inner() below ***. Those random exceptions
455 # don't help anybody, and they confuse users, so we suppress
456 # them. We suppress them only when it appears that the world
457 # indeed has already been destroyed, so that exceptions in
458 # __bootstrap_inner() during normal business hours are properly
459 # reported. Also, we only suppress them for daemonic threads;
460 # if a non-daemonic encounters this, something else is wrong.
462 self
.__bootstrap
_inner
()
464 if self
.__daemonic
and _sys
is None:
468 def __bootstrap_inner(self
):
470 self
.__started
= True
471 _active_limbo_lock
.acquire()
472 _active
[_get_ident()] = self
474 _active_limbo_lock
.release()
476 self
._note
("%s.__bootstrap(): thread started", self
)
479 self
._note
("%s.__bootstrap(): registering trace hook", self
)
480 _sys
.settrace(_trace_hook
)
482 self
._note
("%s.__bootstrap(): registering profile hook", self
)
483 _sys
.setprofile(_profile_hook
)
489 self
._note
("%s.__bootstrap(): raised SystemExit", self
)
492 self
._note
("%s.__bootstrap(): unhandled exception", self
)
493 # If sys.stderr is no more (most likely from interpreter
494 # shutdown) use self.__stderr. Otherwise still use sys (as in
495 # _sys) in case sys.stderr was redefined since the creation of
498 _sys
.stderr
.write("Exception in thread %s:\n%s\n" %
499 (self
.getName(), _format_exc()))
501 # Do the best job possible w/o a huge amt. of code to
502 # approximate a traceback (code ideas from
504 exc_type
, exc_value
, exc_tb
= self
.__exc
_info
()
506 print>>self
.__stderr
, (
507 "Exception in thread " + self
.getName() +
508 " (most likely raised during interpreter shutdown):")
509 print>>self
.__stderr
, (
510 "Traceback (most recent call last):")
512 print>>self
.__stderr
, (
513 ' File "%s", line %s, in %s' %
514 (exc_tb
.tb_frame
.f_code
.co_filename
,
516 exc_tb
.tb_frame
.f_code
.co_name
))
517 exc_tb
= exc_tb
.tb_next
518 print>>self
.__stderr
, ("%s: %s" % (exc_type
, exc_value
))
519 # Make sure that exc_tb gets deleted since it is a memory
520 # hog; deleting everything else is just for thoroughness
522 del exc_type
, exc_value
, exc_tb
525 self
._note
("%s.__bootstrap(): normal return", self
)
534 self
.__block
.acquire()
535 self
.__stopped
= True
536 self
.__block
.notifyAll()
537 self
.__block
.release()
540 "Remove current thread from the dict of currently running threads."
542 # Notes about running with dummy_thread:
544 # Must take care to not raise an exception if dummy_thread is being
545 # used (and thus this module is being used as an instance of
546 # dummy_threading). dummy_thread.get_ident() always returns -1 since
547 # there is only one thread if dummy_thread is being used. Thus
548 # len(_active) is always <= 1 here, and any Thread instance created
549 # overwrites the (if any) thread currently registered in _active.
551 # An instance of _MainThread is always created by 'threading'. This
552 # gets overwritten the instant an instance of Thread is created; both
553 # threads return -1 from dummy_thread.get_ident() and thus have the
554 # same key in the dict. So when the _MainThread instance created by
555 # 'threading' tries to clean itself up when atexit calls this method
556 # it gets a KeyError if another Thread instance was created.
558 # This all means that KeyError from trying to delete something from
559 # _active if dummy_threading is being used is a red herring. But
560 # since it isn't if dummy_threading is *not* being used then don't
561 # hide the exception.
563 _active_limbo_lock
.acquire()
566 del _active
[_get_ident()]
568 if 'dummy_threading' not in _sys
.modules
:
571 _active_limbo_lock
.release()
573 def join(self
, timeout
=None):
574 if not self
.__initialized
:
575 raise RuntimeError("Thread.__init__() not called")
576 if not self
.__started
:
577 raise RuntimeError("cannot join thread before it is started")
578 if self
is currentThread():
579 raise RuntimeError("cannot join current thread")
582 if not self
.__stopped
:
583 self
._note
("%s.join(): waiting until thread stops", self
)
584 self
.__block
.acquire()
587 while not self
.__stopped
:
590 self
._note
("%s.join(): thread stopped", self
)
592 deadline
= _time() + timeout
593 while not self
.__stopped
:
594 delay
= deadline
- _time()
597 self
._note
("%s.join(): timed out", self
)
599 self
.__block
.wait(delay
)
602 self
._note
("%s.join(): thread stopped", self
)
604 self
.__block
.release()
607 assert self
.__initialized
, "Thread.__init__() not called"
610 def setName(self
, name
):
611 assert self
.__initialized
, "Thread.__init__() not called"
612 self
.__name
= str(name
)
615 assert self
.__initialized
, "Thread.__init__() not called"
616 return self
.__started
and not self
.__stopped
619 assert self
.__initialized
, "Thread.__init__() not called"
620 return self
.__daemonic
622 def setDaemon(self
, daemonic
):
623 if not self
.__initialized
:
624 raise RuntimeError("Thread.__init__() not called")
626 raise RuntimeError("cannot set daemon status of active thread");
627 self
.__daemonic
= daemonic
629 # The timer class was contributed by Itamar Shtull-Trauring
631 def Timer(*args
, **kwargs
):
632 return _Timer(*args
, **kwargs
)
634 class _Timer(Thread
):
635 """Call a function after a specified number of seconds:
637 t = Timer(30.0, f, args=[], kwargs={})
639 t.cancel() # stop the timer's action if it's still waiting
642 def __init__(self
, interval
, function
, args
=[], kwargs
={}):
643 Thread
.__init
__(self
)
644 self
.interval
= interval
645 self
.function
= function
648 self
.finished
= Event()
651 """Stop the timer if it hasn't finished yet"""
655 self
.finished
.wait(self
.interval
)
656 if not self
.finished
.isSet():
657 self
.function(*self
.args
, **self
.kwargs
)
660 # Special thread class to represent the main thread
661 # This is garbage collected through an exit handler
663 class _MainThread(Thread
):
666 Thread
.__init
__(self
, name
="MainThread")
667 self
._Thread
__started
= True
668 _active_limbo_lock
.acquire()
669 _active
[_get_ident()] = self
670 _active_limbo_lock
.release()
672 def _set_daemon(self
):
677 t
= _pickSomeNonDaemonThread()
680 self
._note
("%s: waiting for other threads", self
)
683 t
= _pickSomeNonDaemonThread()
685 self
._note
("%s: exiting", self
)
686 self
._Thread
__delete
()
688 def _pickSomeNonDaemonThread():
689 for t
in enumerate():
690 if not t
.isDaemon() and t
.isAlive():
695 # Dummy thread class to represent threads not started here.
696 # These aren't garbage collected when they die, nor can they be waited for.
697 # If they invoke anything in threading.py that calls currentThread(), they
698 # leave an entry in the _active dict forever after.
699 # Their purpose is to return *something* from currentThread().
700 # They are marked as daemon threads so we won't wait for them
701 # when we exit (conform previous semantics).
703 class _DummyThread(Thread
):
706 Thread
.__init
__(self
, name
=_newname("Dummy-%d"))
708 # Thread.__block consumes an OS-level locking primitive, which
709 # can never be used by a _DummyThread. Since a _DummyThread
710 # instance is immortal, that's bad, so release this resource.
711 del self
._Thread
__block
713 self
._Thread
__started
= True
714 _active_limbo_lock
.acquire()
715 _active
[_get_ident()] = self
716 _active_limbo_lock
.release()
718 def _set_daemon(self
):
721 def join(self
, timeout
=None):
722 assert False, "cannot join a dummy thread"
725 # Global API functions
729 return _active
[_get_ident()]
731 ##print "currentThread(): no current thread for", _get_ident()
732 return _DummyThread()
735 _active_limbo_lock
.acquire()
736 count
= len(_active
) + len(_limbo
)
737 _active_limbo_lock
.release()
741 _active_limbo_lock
.acquire()
742 active
= _active
.values() + _limbo
.values()
743 _active_limbo_lock
.release()
746 from thread
import stack_size
748 # Create the main thread object,
749 # and make it available for the interpreter
750 # (Py_Main) as threading._shutdown.
752 _shutdown
= _MainThread()._exitfunc
754 # get thread-local implementation, either from the thread
755 # module, or from the python fallback
758 from thread
import _local
as local
760 from _threading_local
import local
767 class BoundedQueue(_Verbose
):
769 def __init__(self
, limit
):
770 _Verbose
.__init
__(self
)
772 self
.rc
= Condition(self
.mon
)
773 self
.wc
= Condition(self
.mon
)
779 while len(self
.queue
) >= self
.limit
:
780 self
._note
("put(%s): queue full", item
)
782 self
.queue
.append(item
)
783 self
._note
("put(%s): appended, length now %d",
784 item
, len(self
.queue
))
790 while not self
.queue
:
791 self
._note
("get(): queue empty")
793 item
= self
.queue
.popleft()
794 self
._note
("get(): got %s, %d left", item
, len(self
.queue
))
799 class ProducerThread(Thread
):
801 def __init__(self
, queue
, quota
):
802 Thread
.__init
__(self
, name
="Producer")
807 from random
import random
809 while counter
< self
.quota
:
810 counter
= counter
+ 1
811 self
.queue
.put("%s.%d" % (self
.getName(), counter
))
812 _sleep(random() * 0.00001)
815 class ConsumerThread(Thread
):
817 def __init__(self
, queue
, count
):
818 Thread
.__init
__(self
, name
="Consumer")
823 while self
.count
> 0:
824 item
= self
.queue
.get()
826 self
.count
= self
.count
- 1
835 t
= ProducerThread(Q
, NI
)
836 t
.setName("Producer-%d" % (i
+1))
838 C
= ConsumerThread(Q
, NI
*NP
)
847 if __name__
== '__main__':