1 """Thread module emulating a subset of Java's threading model."""
6 from time
import time
as _time
, sleep
as _sleep
7 from traceback
import format_exc
as _format_exc
8 from collections
import deque
10 # Note regarding PEP 8 compliant names
11 # This threading model was originally inspired by Java, and inherited
12 # the convention of camelCase function and method names from that
13 # language. Those originaly names are not in any imminent danger of
14 # being deprecated (even for Py3k),so this module provides them as an
15 # alias for the PEP 8 compliant names
16 # Note that using the new PEP 8 compliant names facilitates substitution
17 # with the multiprocessing module, which doesn't provide the old
18 # Java inspired names.
21 # Rename some stuff so "from threading import *" is safe
22 __all__
= ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
23 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
24 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
26 _start_new_thread
= _thread
.start_new_thread
27 _allocate_lock
= _thread
.allocate_lock
28 _get_ident
= _thread
.get_ident
29 ThreadError
= _thread
.error
33 # Debug support (adapted from ihooks.py).
34 # All the major classes here derive from _Verbose. We force that to
35 # be a new-style class so that all the major classes here are new-style.
36 # This helps debugging (type(instance) is more revealing for instances
37 # of new-style classes).
43 class _Verbose(object):
45 def __init__(self
, verbose
=None):
48 self
._verbose
= verbose
50 def _note(self
, format
, *args
):
52 format
= format
% args
53 format
= "%s: %s\n" % (
54 current_thread().name
, format
)
55 _sys
.stderr
.write(format
)
58 # Disable this when using "python -O"
59 class _Verbose(object):
60 def __init__(self
, verbose
=None):
62 def _note(self
, *args
):
65 # Support for profile and trace hooks
78 # Synchronization classes
82 def RLock(*args
, **kwargs
):
83 return _RLock(*args
, **kwargs
)
85 class _RLock(_Verbose
):
87 def __init__(self
, verbose
=None):
88 _Verbose
.__init
__(self
, verbose
)
89 self
._block
= _allocate_lock()
96 owner
= _active
[owner
].name
99 return "<%s owner=%r count=%d>" % (
100 self
.__class
__.__name
__, owner
, self
._count
)
102 def acquire(self
, blocking
=True):
104 if self
._owner
== me
:
105 self
._count
= self
._count
+ 1
107 self
._note
("%s.acquire(%s): recursive success", self
, blocking
)
109 rc
= self
._block
.acquire(blocking
)
114 self
._note
("%s.acquire(%s): initial success", self
, blocking
)
117 self
._note
("%s.acquire(%s): failure", self
, blocking
)
123 if self
._owner
!= _get_ident():
124 raise RuntimeError("cannot release un-acquired lock")
125 self
._count
= count
= self
._count
- 1
128 self
._block
.release()
130 self
._note
("%s.release(): final release", self
)
133 self
._note
("%s.release(): non-final release", self
)
135 def __exit__(self
, t
, v
, tb
):
138 # Internal methods used by condition variables
140 def _acquire_restore(self
, state
):
141 self
._block
.acquire()
142 self
._count
, self
._owner
= state
144 self
._note
("%s._acquire_restore()", self
)
146 def _release_save(self
):
148 self
._note
("%s._release_save()", self
)
153 self
._block
.release()
154 return (count
, owner
)
157 return self
._owner
== _get_ident()
160 def Condition(*args
, **kwargs
):
161 return _Condition(*args
, **kwargs
)
163 class _Condition(_Verbose
):
165 def __init__(self
, lock
=None, verbose
=None):
166 _Verbose
.__init
__(self
, verbose
)
170 # Export the lock's acquire() and release() methods
171 self
.acquire
= lock
.acquire
172 self
.release
= lock
.release
173 # If the lock defines _release_save() and/or _acquire_restore(),
174 # these override the default implementations (which just call
175 # release() and acquire() on the lock). Ditto for _is_owned().
177 self
._release
_save
= lock
._release
_save
178 except AttributeError:
181 self
._acquire
_restore
= lock
._acquire
_restore
182 except AttributeError:
185 self
._is
_owned
= lock
._is
_owned
186 except AttributeError:
191 return self
._lock
.__enter
__()
193 def __exit__(self
, *args
):
194 return self
._lock
.__exit
__(*args
)
197 return "<Condition(%s, %d)>" % (self
._lock
, len(self
._waiters
))
199 def _release_save(self
):
200 self
._lock
.release() # No state to save
202 def _acquire_restore(self
, x
):
203 self
._lock
.acquire() # Ignore saved state
206 # Return True if lock is owned by current_thread.
207 # This method is called only if __lock doesn't have _is_owned().
208 if self
._lock
.acquire(0):
214 def wait(self
, timeout
=None):
215 if not self
._is
_owned
():
216 raise RuntimeError("cannot wait on un-acquired lock")
217 waiter
= _allocate_lock()
219 self
._waiters
.append(waiter
)
220 saved_state
= self
._release
_save
()
221 try: # restore state no matter what (e.g., KeyboardInterrupt)
225 self
._note
("%s.wait(): got it", self
)
227 # Balancing act: We can't afford a pure busy loop, so we
228 # have to sleep; but if we sleep the whole timeout time,
229 # we'll be unresponsive. The scheme here sleeps very
230 # little at first, longer as time goes on, but never longer
231 # than 20 times per second (or the timeout time remaining).
232 endtime
= _time() + timeout
233 delay
= 0.0005 # 500 us -> initial delay of 1 ms
235 gotit
= waiter
.acquire(0)
238 remaining
= endtime
- _time()
241 delay
= min(delay
* 2, remaining
, .05)
245 self
._note
("%s.wait(%s): timed out", self
, timeout
)
247 self
._waiters
.remove(waiter
)
252 self
._note
("%s.wait(%s): got it", self
, timeout
)
254 self
._acquire
_restore
(saved_state
)
256 def notify(self
, n
=1):
257 if not self
._is
_owned
():
258 raise RuntimeError("cannot notify on un-acquired lock")
259 __waiters
= self
._waiters
260 waiters
= __waiters
[:n
]
263 self
._note
("%s.notify(): no waiters", self
)
265 self
._note
("%s.notify(): notifying %d waiter%s", self
, n
,
267 for waiter
in waiters
:
270 __waiters
.remove(waiter
)
274 def notify_all(self
):
275 self
.notify(len(self
._waiters
))
277 notifyAll
= notify_all
280 def Semaphore(*args
, **kwargs
):
281 return _Semaphore(*args
, **kwargs
)
283 class _Semaphore(_Verbose
):
285 # After Tim Peters' semaphore class, but not quite the same (no maximum)
287 def __init__(self
, value
=1, verbose
=None):
289 raise ValueError("semaphore initial value must be >= 0")
290 _Verbose
.__init
__(self
, verbose
)
291 self
._cond
= Condition(Lock())
294 def acquire(self
, blocking
=True):
297 while self
._value
== 0:
301 self
._note
("%s.acquire(%s): blocked waiting, value=%s",
302 self
, blocking
, self
._value
)
305 self
._value
= self
._value
- 1
307 self
._note
("%s.acquire: success, value=%s",
317 self
._value
= self
._value
+ 1
319 self
._note
("%s.release: success, value=%s",
324 def __exit__(self
, t
, v
, tb
):
328 def BoundedSemaphore(*args
, **kwargs
):
329 return _BoundedSemaphore(*args
, **kwargs
)
331 class _BoundedSemaphore(_Semaphore
):
332 """Semaphore that checks that # releases is <= # acquires"""
333 def __init__(self
, value
=1, verbose
=None):
334 _Semaphore
.__init
__(self
, value
, verbose
)
335 self
._initial
_value
= value
338 if self
._value
>= self
._initial
_value
:
339 raise ValueError("Semaphore released too many times")
340 return _Semaphore
.release(self
)
343 def Event(*args
, **kwargs
):
344 return _Event(*args
, **kwargs
)
346 class _Event(_Verbose
):
348 # After Tim Peters' event class (without is_posted())
350 def __init__(self
, verbose
=None):
351 _Verbose
.__init
__(self
, verbose
)
352 self
._cond
= Condition(Lock())
364 self
._cond
.notify_all()
375 def wait(self
, timeout
=None):
379 self
._cond
.wait(timeout
)
384 # Helper to generate new thread names
386 def _newname(template
="Thread-%d"):
388 _counter
= _counter
+ 1
389 return template
% _counter
391 # Active thread administration
392 _active_limbo_lock
= _allocate_lock()
393 _active
= {} # maps thread id to Thread object
397 # Main class for threads
399 class Thread(_Verbose
):
401 __initialized
= False
402 # Need to store a reference to sys.exc_info for printing
403 # out exceptions when a thread tries to use a global var. during interp.
404 # shutdown and thus raises an exception about trying to perform some
405 # operation on/with a NoneType
406 __exc_info
= _sys
.exc_info
407 # Keep sys.exc_clear too to clear the exception just before
408 # allowing .join() to return.
409 #XXX __exc_clear = _sys.exc_clear
411 def __init__(self
, group
=None, target
=None, name
=None,
412 args
=(), kwargs
=None, verbose
=None):
413 assert group
is None, "group argument must be None for now"
414 _Verbose
.__init
__(self
, verbose
)
417 self
._target
= target
418 self
._name
= str(name
or _newname())
420 self
._kwargs
= kwargs
421 self
._daemonic
= self
._set
_daemon
()
423 self
._started
= Event()
424 self
._stopped
= False
425 self
._block
= Condition(Lock())
426 self
._initialized
= True
427 # sys.stderr is not stored in the class like
428 # sys.exc_info since it can be changed between instances
429 self
._stderr
= _sys
.stderr
431 def _set_daemon(self
):
432 # Overridden in _MainThread and _DummyThread
433 return current_thread().daemon
436 assert self
._initialized
, "Thread.__init__() was not called"
438 if self
._started
.is_set():
444 if self
._ident
is not None:
445 status
+= " %s" % self
._ident
446 return "<%s(%s, %s)>" % (self
.__class
__.__name
__, self
._name
, status
)
449 if not self
._initialized
:
450 raise RuntimeError("thread.__init__() not called")
452 if self
._started
.is_set():
453 raise RuntimeError("thread already started")
455 self
._note
("%s.start(): starting thread", self
)
456 with _active_limbo_lock
:
459 _start_new_thread(self
._bootstrap
, ())
461 with _active_limbo_lock
:
469 self
._target
(*self
._args
, **self
._kwargs
)
471 # Avoid a refcycle if the thread is running a function with
472 # an argument that has a member that points to the thread.
473 del self
._target
, self
._args
, self
._kwargs
475 def _bootstrap(self
):
476 # Wrapper around the real bootstrap code that ignores
477 # exceptions during interpreter cleanup. Those typically
478 # happen when a daemon thread wakes up at an unfortunate
479 # moment, finds the world around it destroyed, and raises some
480 # random exception *** while trying to report the exception in
481 # _bootstrap_inner() below ***. Those random exceptions
482 # don't help anybody, and they confuse users, so we suppress
483 # them. We suppress them only when it appears that the world
484 # indeed has already been destroyed, so that exceptions in
485 # _bootstrap_inner() during normal business hours are properly
486 # reported. Also, we only suppress them for daemonic threads;
487 # if a non-daemonic encounters this, something else is wrong.
489 self
._bootstrap
_inner
()
491 if self
._daemonic
and _sys
is None:
495 def _set_ident(self
):
496 self
._ident
= _get_ident()
498 def _bootstrap_inner(self
):
502 with _active_limbo_lock
:
503 _active
[self
._ident
] = self
506 self
._note
("%s._bootstrap(): thread started", self
)
509 self
._note
("%s._bootstrap(): registering trace hook", self
)
510 _sys
.settrace(_trace_hook
)
512 self
._note
("%s._bootstrap(): registering profile hook", self
)
513 _sys
.setprofile(_profile_hook
)
519 self
._note
("%s._bootstrap(): raised SystemExit", self
)
522 self
._note
("%s._bootstrap(): unhandled exception", self
)
523 # If sys.stderr is no more (most likely from interpreter
524 # shutdown) use self._stderr. Otherwise still use sys (as in
525 # _sys) in case sys.stderr was redefined since the creation of
528 _sys
.stderr
.write("Exception in thread %s:\n%s\n" %
529 (self
.name
, _format_exc()))
531 # Do the best job possible w/o a huge amt. of code to
532 # approximate a traceback (code ideas from
534 exc_type
, exc_value
, exc_tb
= self
._exc
_info
()
537 "Exception in thread " + self
.name
+
538 " (most likely raised during interpreter shutdown):"), file=self
._stderr
)
540 "Traceback (most recent call last):"), file=self
._stderr
)
543 ' File "%s", line %s, in %s' %
544 (exc_tb
.tb_frame
.f_code
.co_filename
,
546 exc_tb
.tb_frame
.f_code
.co_name
)), file=self
._stderr
)
547 exc_tb
= exc_tb
.tb_next
548 print(("%s: %s" % (exc_type
, exc_value
)), file=self
._stderr
)
549 # Make sure that exc_tb gets deleted since it is a memory
550 # hog; deleting everything else is just for thoroughness
552 del exc_type
, exc_value
, exc_tb
555 self
._note
("%s._bootstrap(): normal return", self
)
558 # test_threading.test_no_refcycle_through_target when
559 # the exception keeps the target alive past when we
560 # assert that it's dead.
561 #XXX self.__exc_clear()
564 with _active_limbo_lock
:
567 # We don't call self._delete() because it also
568 # grabs _active_limbo_lock.
569 del _active
[_get_ident()]
574 self
._block
.acquire()
576 self
._block
.notify_all()
577 self
._block
.release()
580 "Remove current thread from the dict of currently running threads."
582 # Notes about running with _dummy_thread:
584 # Must take care to not raise an exception if _dummy_thread is being
585 # used (and thus this module is being used as an instance of
586 # dummy_threading). _dummy_thread.get_ident() always returns -1 since
587 # there is only one thread if _dummy_thread is being used. Thus
588 # len(_active) is always <= 1 here, and any Thread instance created
589 # overwrites the (if any) thread currently registered in _active.
591 # An instance of _MainThread is always created by 'threading'. This
592 # gets overwritten the instant an instance of Thread is created; both
593 # threads return -1 from _dummy_thread.get_ident() and thus have the
594 # same key in the dict. So when the _MainThread instance created by
595 # 'threading' tries to clean itself up when atexit calls this method
596 # it gets a KeyError if another Thread instance was created.
598 # This all means that KeyError from trying to delete something from
599 # _active if dummy_threading is being used is a red herring. But
600 # since it isn't if dummy_threading is *not* being used then don't
601 # hide the exception.
604 with _active_limbo_lock
:
605 del _active
[_get_ident()]
606 # There must not be any python code between the previous line
607 # and after the lock is released. Otherwise a tracing function
608 # could try to acquire the lock again in the same thread, (in
609 # current_thread()), and would block.
611 if 'dummy_threading' not in _sys
.modules
:
614 def join(self
, timeout
=None):
615 if not self
._initialized
:
616 raise RuntimeError("Thread.__init__() not called")
617 if not self
._started
.is_set():
618 raise RuntimeError("cannot join thread before it is started")
619 if self
is current_thread():
620 raise RuntimeError("cannot join current thread")
623 if not self
._stopped
:
624 self
._note
("%s.join(): waiting until thread stops", self
)
626 self
._block
.acquire()
629 while not self
._stopped
:
632 self
._note
("%s.join(): thread stopped", self
)
634 deadline
= _time() + timeout
635 while not self
._stopped
:
636 delay
= deadline
- _time()
639 self
._note
("%s.join(): timed out", self
)
641 self
._block
.wait(delay
)
644 self
._note
("%s.join(): thread stopped", self
)
646 self
._block
.release()
650 assert self
._initialized
, "Thread.__init__() not called"
654 def name(self
, name
):
655 assert self
._initialized
, "Thread.__init__() not called"
656 self
._name
= str(name
)
660 assert self
._initialized
, "Thread.__init__() not called"
664 assert self
._initialized
, "Thread.__init__() not called"
665 return self
._started
.is_set() and not self
._stopped
671 assert self
._initialized
, "Thread.__init__() not called"
672 return self
._daemonic
675 def daemon(self
, daemonic
):
676 if not self
._initialized
:
677 raise RuntimeError("Thread.__init__() not called")
678 if self
._started
.is_set():
679 raise RuntimeError("cannot set daemon status of active thread");
680 self
._daemonic
= daemonic
685 def setDaemon(self
, daemonic
):
686 self
.daemon
= daemonic
691 def setName(self
, name
):
694 # The timer class was contributed by Itamar Shtull-Trauring
696 def Timer(*args
, **kwargs
):
697 return _Timer(*args
, **kwargs
)
699 class _Timer(Thread
):
700 """Call a function after a specified number of seconds:
702 t = Timer(30.0, f, args=[], kwargs={})
704 t.cancel() # stop the timer's action if it's still waiting
707 def __init__(self
, interval
, function
, args
=[], kwargs
={}):
708 Thread
.__init
__(self
)
709 self
.interval
= interval
710 self
.function
= function
713 self
.finished
= Event()
716 """Stop the timer if it hasn't finished yet"""
720 self
.finished
.wait(self
.interval
)
721 if not self
.finished
.is_set():
722 self
.function(*self
.args
, **self
.kwargs
)
725 # Special thread class to represent the main thread
726 # This is garbage collected through an exit handler
728 class _MainThread(Thread
):
731 Thread
.__init
__(self
, name
="MainThread")
734 with _active_limbo_lock
:
735 _active
[self
._ident
] = self
737 def _set_daemon(self
):
742 t
= _pickSomeNonDaemonThread()
745 self
._note
("%s: waiting for other threads", self
)
748 t
= _pickSomeNonDaemonThread()
750 self
._note
("%s: exiting", self
)
753 def _pickSomeNonDaemonThread():
754 for t
in enumerate():
755 if not t
.daemon
and t
.is_alive():
760 # Dummy thread class to represent threads not started here.
761 # These aren't garbage collected when they die, nor can they be waited for.
762 # If they invoke anything in threading.py that calls current_thread(), they
763 # leave an entry in the _active dict forever after.
764 # Their purpose is to return *something* from current_thread().
765 # They are marked as daemon threads so we won't wait for them
766 # when we exit (conform previous semantics).
768 class _DummyThread(Thread
):
771 Thread
.__init
__(self
, name
=_newname("Dummy-%d"))
773 # Thread.__block consumes an OS-level locking primitive, which
774 # can never be used by a _DummyThread. Since a _DummyThread
775 # instance is immortal, that's bad, so release this resource.
781 with _active_limbo_lock
:
782 _active
[self
._ident
] = self
784 def _set_daemon(self
):
787 def join(self
, timeout
=None):
788 assert False, "cannot join a dummy thread"
791 # Global API functions
793 def current_thread():
795 return _active
[_get_ident()]
797 ##print "current_thread(): no current thread for", _get_ident()
798 return _DummyThread()
800 currentThread
= current_thread
803 with _active_limbo_lock
:
804 return len(_active
) + len(_limbo
)
806 activeCount
= active_count
809 # Same as enumerate(), but without the lock. Internal use only.
810 return list(_active
.values()) + list(_limbo
.values())
813 with _active_limbo_lock
:
814 return list(_active
.values()) + list(_limbo
.values())
816 from _thread
import stack_size
818 # Create the main thread object,
819 # and make it available for the interpreter
820 # (Py_Main) as threading._shutdown.
822 _shutdown
= _MainThread()._exitfunc
824 # get thread-local implementation, either from the thread
825 # module, or from the python fallback
828 from _thread
import _local
as local
830 from _threading_local
import local
834 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
835 # is called from PyOS_AfterFork. Here we cleanup threading module state
836 # that should not exist after a fork.
838 # Reset _active_limbo_lock, in case we forked while the lock was held
839 # by another (non-forked) thread. http://bugs.python.org/issue874900
840 global _active_limbo_lock
841 _active_limbo_lock
= _allocate_lock()
843 # fork() only copied the current thread; clear references to others.
845 current
= current_thread()
846 with _active_limbo_lock
:
847 for thread
in _active
.values():
848 if thread
is current
:
849 # There is only one active thread. We reset the ident to
850 # its new value since it can have changed.
852 thread
._ident
= ident
853 new_active
[ident
] = thread
855 # All the others are already stopped.
856 # We don't call _Thread__stop() because it tries to acquire
857 # thread._Thread__block which could also have been held while
859 thread
._stopped
= True
863 _active
.update(new_active
)
864 assert len(_active
) == 1
871 class BoundedQueue(_Verbose
):
873 def __init__(self
, limit
):
874 _Verbose
.__init
__(self
)
876 self
.rc
= Condition(self
.mon
)
877 self
.wc
= Condition(self
.mon
)
883 while len(self
.queue
) >= self
.limit
:
884 self
._note
("put(%s): queue full", item
)
886 self
.queue
.append(item
)
887 self
._note
("put(%s): appended, length now %d",
888 item
, len(self
.queue
))
894 while not self
.queue
:
895 self
._note
("get(): queue empty")
897 item
= self
.queue
.popleft()
898 self
._note
("get(): got %s, %d left", item
, len(self
.queue
))
903 class ProducerThread(Thread
):
905 def __init__(self
, queue
, quota
):
906 Thread
.__init
__(self
, name
="Producer")
911 from random
import random
913 while counter
< self
.quota
:
914 counter
= counter
+ 1
915 self
.queue
.put("%s.%d" % (self
.name
, counter
))
916 _sleep(random() * 0.00001)
919 class ConsumerThread(Thread
):
921 def __init__(self
, queue
, count
):
922 Thread
.__init
__(self
, name
="Consumer")
927 while self
.count
> 0:
928 item
= self
.queue
.get()
930 self
.count
= self
.count
- 1
939 t
= ProducerThread(Q
, NI
)
940 t
.name
= "Producer-%d" % (i
+1)
942 C
= ConsumerThread(Q
, NI
*NP
)
951 if __name__
== '__main__':