1 """Thread module emulating a subset of Java's threading model."""
8 del _sys
.modules
[__name__
]
13 from functools
import wraps
14 from time
import time
as _time
, sleep
as _sleep
15 from traceback
import format_exc
as _format_exc
16 from collections
import deque
18 # Note regarding PEP 8 compliant aliases
19 # This threading model was originally inspired by Java, and inherited
20 # the convention of camelCase function and method names from that
21 # language. While those names are not in any imminent danger of being
22 # deprecated, starting with Python 2.6, the module now provides a
23 # PEP 8 compliant alias for any such method name.
24 # Using the new PEP 8 compliant names also facilitates substitution
25 # with the multiprocessing module, which doesn't provide the old
26 # Java inspired names.
29 # Rename some stuff so "from threading import *" is safe
30 __all__
= ['activeCount', 'active_count', 'Condition', 'currentThread',
31 'current_thread', 'enumerate', 'Event',
32 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
33 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
35 _start_new_thread
= thread
.start_new_thread
36 _allocate_lock
= thread
.allocate_lock
37 _get_ident
= thread
.get_ident
38 ThreadError
= thread
.error
42 # sys.exc_clear is used to work around the fact that except blocks
43 # don't fully clear the exception until 3.0.
44 warnings
.filterwarnings('ignore', category
=DeprecationWarning,
45 module
='threading', message
='sys.exc_clear')
47 # Debug support (adapted from ihooks.py).
48 # All the major classes here derive from _Verbose. We force that to
49 # be a new-style class so that all the major classes here are new-style.
50 # This helps debugging (type(instance) is more revealing for instances
51 # of new-style classes).
57 class _Verbose(object):
59 def __init__(self
, verbose
=None):
62 self
.__verbose
= verbose
64 def _note(self
, format
, *args
):
66 format
= format
% args
67 format
= "%s: %s\n" % (
68 current_thread().name
, format
)
69 _sys
.stderr
.write(format
)
72 # Disable this when using "python -O"
73 class _Verbose(object):
74 def __init__(self
, verbose
=None):
76 def _note(self
, *args
):
79 # Support for profile and trace hooks
92 # Synchronization classes
96 def RLock(*args
, **kwargs
):
97 return _RLock(*args
, **kwargs
)
99 class _RLock(_Verbose
):
101 def __init__(self
, verbose
=None):
102 _Verbose
.__init
__(self
, verbose
)
103 self
.__block
= _allocate_lock()
109 return "<%s(%s, %d)>" % (
110 self
.__class
__.__name
__,
111 owner
and owner
.name
,
114 def acquire(self
, blocking
=1):
115 me
= current_thread()
116 if self
.__owner
is me
:
117 self
.__count
= self
.__count
+ 1
119 self
._note
("%s.acquire(%s): recursive success", self
, blocking
)
121 rc
= self
.__block
.acquire(blocking
)
126 self
._note
("%s.acquire(%s): initial success", self
, blocking
)
129 self
._note
("%s.acquire(%s): failure", self
, blocking
)
135 if self
.__owner
is not current_thread():
136 raise RuntimeError("cannot release un-acquired lock")
137 self
.__count
= count
= self
.__count
- 1
140 self
.__block
.release()
142 self
._note
("%s.release(): final release", self
)
145 self
._note
("%s.release(): non-final release", self
)
147 def __exit__(self
, t
, v
, tb
):
150 # Internal methods used by condition variables
152 def _acquire_restore(self
, count_owner
):
153 count
, owner
= count_owner
154 self
.__block
.acquire()
158 self
._note
("%s._acquire_restore()", self
)
160 def _release_save(self
):
162 self
._note
("%s._release_save()", self
)
167 self
.__block
.release()
168 return (count
, owner
)
171 return self
.__owner
is current_thread()
174 def Condition(*args
, **kwargs
):
175 return _Condition(*args
, **kwargs
)
177 class _Condition(_Verbose
):
179 def __init__(self
, lock
=None, verbose
=None):
180 _Verbose
.__init
__(self
, verbose
)
184 # Export the lock's acquire() and release() methods
185 self
.acquire
= lock
.acquire
186 self
.release
= lock
.release
187 # If the lock defines _release_save() and/or _acquire_restore(),
188 # these override the default implementations (which just call
189 # release() and acquire() on the lock). Ditto for _is_owned().
191 self
._release
_save
= lock
._release
_save
192 except AttributeError:
195 self
._acquire
_restore
= lock
._acquire
_restore
196 except AttributeError:
199 self
._is
_owned
= lock
._is
_owned
200 except AttributeError:
205 return self
.__lock
.__enter
__()
207 def __exit__(self
, *args
):
208 return self
.__lock
.__exit
__(*args
)
211 return "<Condition(%s, %d)>" % (self
.__lock
, len(self
.__waiters
))
213 def _release_save(self
):
214 self
.__lock
.release() # No state to save
216 def _acquire_restore(self
, x
):
217 self
.__lock
.acquire() # Ignore saved state
220 # Return True if lock is owned by current_thread.
221 # This method is called only if __lock doesn't have _is_owned().
222 if self
.__lock
.acquire(0):
223 self
.__lock
.release()
228 def wait(self
, timeout
=None):
229 if not self
._is
_owned
():
230 raise RuntimeError("cannot wait on un-acquired lock")
231 waiter
= _allocate_lock()
233 self
.__waiters
.append(waiter
)
234 saved_state
= self
._release
_save
()
235 try: # restore state no matter what (e.g., KeyboardInterrupt)
239 self
._note
("%s.wait(): got it", self
)
241 # Balancing act: We can't afford a pure busy loop, so we
242 # have to sleep; but if we sleep the whole timeout time,
243 # we'll be unresponsive. The scheme here sleeps very
244 # little at first, longer as time goes on, but never longer
245 # than 20 times per second (or the timeout time remaining).
246 endtime
= _time() + timeout
247 delay
= 0.0005 # 500 us -> initial delay of 1 ms
249 gotit
= waiter
.acquire(0)
252 remaining
= endtime
- _time()
255 delay
= min(delay
* 2, remaining
, .05)
259 self
._note
("%s.wait(%s): timed out", self
, timeout
)
261 self
.__waiters
.remove(waiter
)
266 self
._note
("%s.wait(%s): got it", self
, timeout
)
268 self
._acquire
_restore
(saved_state
)
270 def notify(self
, n
=1):
271 if not self
._is
_owned
():
272 raise RuntimeError("cannot notify on un-acquired lock")
273 __waiters
= self
.__waiters
274 waiters
= __waiters
[:n
]
277 self
._note
("%s.notify(): no waiters", self
)
279 self
._note
("%s.notify(): notifying %d waiter%s", self
, n
,
281 for waiter
in waiters
:
284 __waiters
.remove(waiter
)
289 self
.notify(len(self
.__waiters
))
291 notify_all
= notifyAll
294 def Semaphore(*args
, **kwargs
):
295 return _Semaphore(*args
, **kwargs
)
297 class _Semaphore(_Verbose
):
299 # After Tim Peters' semaphore class, but not quite the same (no maximum)
301 def __init__(self
, value
=1, verbose
=None):
303 raise ValueError("semaphore initial value must be >= 0")
304 _Verbose
.__init
__(self
, verbose
)
305 self
.__cond
= Condition(Lock())
308 def acquire(self
, blocking
=1):
310 self
.__cond
.acquire()
311 while self
.__value
== 0:
315 self
._note
("%s.acquire(%s): blocked waiting, value=%s",
316 self
, blocking
, self
.__value
)
319 self
.__value
= self
.__value
- 1
321 self
._note
("%s.acquire: success, value=%s",
324 self
.__cond
.release()
330 self
.__cond
.acquire()
331 self
.__value
= self
.__value
+ 1
333 self
._note
("%s.release: success, value=%s",
336 self
.__cond
.release()
338 def __exit__(self
, t
, v
, tb
):
342 def BoundedSemaphore(*args
, **kwargs
):
343 return _BoundedSemaphore(*args
, **kwargs
)
345 class _BoundedSemaphore(_Semaphore
):
346 """Semaphore that checks that # releases is <= # acquires"""
347 def __init__(self
, value
=1, verbose
=None):
348 _Semaphore
.__init
__(self
, value
, verbose
)
349 self
._initial
_value
= value
352 if self
._Semaphore
__value
>= self
._initial
_value
:
353 raise ValueError, "Semaphore released too many times"
354 return _Semaphore
.release(self
)
357 def Event(*args
, **kwargs
):
358 return _Event(*args
, **kwargs
)
360 class _Event(_Verbose
):
362 # After Tim Peters' event class (without is_posted())
364 def __init__(self
, verbose
=None):
365 _Verbose
.__init
__(self
, verbose
)
366 self
.__cond
= Condition(Lock())
375 self
.__cond
.acquire()
378 self
.__cond
.notify_all()
380 self
.__cond
.release()
383 self
.__cond
.acquire()
387 self
.__cond
.release()
389 def wait(self
, timeout
=None):
390 self
.__cond
.acquire()
393 self
.__cond
.wait(timeout
)
396 self
.__cond
.release()
398 # Helper to generate new thread names
400 def _newname(template
="Thread-%d"):
402 _counter
= _counter
+ 1
403 return template
% _counter
405 # Active thread administration
406 _active_limbo_lock
= _allocate_lock()
407 _active
= {} # maps thread id to Thread object
411 # Main class for threads
413 class Thread(_Verbose
):
415 __initialized
= False
416 # Need to store a reference to sys.exc_info for printing
417 # out exceptions when a thread tries to use a global var. during interp.
418 # shutdown and thus raises an exception about trying to perform some
419 # operation on/with a NoneType
420 __exc_info
= _sys
.exc_info
421 # Keep sys.exc_clear too to clear the exception just before
422 # allowing .join() to return.
423 __exc_clear
= _sys
.exc_clear
425 def __init__(self
, group
=None, target
=None, name
=None,
426 args
=(), kwargs
=None, verbose
=None):
427 assert group
is None, "group argument must be None for now"
428 _Verbose
.__init
__(self
, verbose
)
431 self
.__target
= target
432 self
.__name
= str(name
or _newname())
434 self
.__kwargs
= kwargs
435 self
.__daemonic
= self
._set
_daemon
()
437 self
.__started
= Event()
438 self
.__stopped
= False
439 self
.__block
= Condition(Lock())
440 self
.__initialized
= True
441 # sys.stderr is not stored in the class like
442 # sys.exc_info since it can be changed between instances
443 self
.__stderr
= _sys
.stderr
445 def _set_daemon(self
):
446 # Overridden in _MainThread and _DummyThread
447 return current_thread().daemon
450 assert self
.__initialized
, "Thread.__init__() was not called"
452 if self
.__started
.is_set():
458 if self
.__ident
is not None:
459 status
+= " %s" % self
.__ident
460 return "<%s(%s, %s)>" % (self
.__class
__.__name
__, self
.__name
, status
)
463 if not self
.__initialized
:
464 raise RuntimeError("thread.__init__() not called")
465 if self
.__started
.is_set():
466 raise RuntimeError("thread already started")
468 self
._note
("%s.start(): starting thread", self
)
469 with _active_limbo_lock
:
471 _start_new_thread(self
.__bootstrap
, ())
472 self
.__started
.wait()
477 self
.__target
(*self
.__args
, **self
.__kwargs
)
479 # Avoid a refcycle if the thread is running a function with
480 # an argument that has a member that points to the thread.
481 del self
.__target
, self
.__args
, self
.__kwargs
483 def __bootstrap(self
):
484 # Wrapper around the real bootstrap code that ignores
485 # exceptions during interpreter cleanup. Those typically
486 # happen when a daemon thread wakes up at an unfortunate
487 # moment, finds the world around it destroyed, and raises some
488 # random exception *** while trying to report the exception in
489 # __bootstrap_inner() below ***. Those random exceptions
490 # don't help anybody, and they confuse users, so we suppress
491 # them. We suppress them only when it appears that the world
492 # indeed has already been destroyed, so that exceptions in
493 # __bootstrap_inner() during normal business hours are properly
494 # reported. Also, we only suppress them for daemonic threads;
495 # if a non-daemonic encounters this, something else is wrong.
497 self
.__bootstrap
_inner
()
499 if self
.__daemonic
and _sys
is None:
503 def _set_ident(self
):
504 self
.__ident
= _get_ident()
506 def __bootstrap_inner(self
):
510 with _active_limbo_lock
:
511 _active
[self
.__ident
] = self
514 self
._note
("%s.__bootstrap(): thread started", self
)
517 self
._note
("%s.__bootstrap(): registering trace hook", self
)
518 _sys
.settrace(_trace_hook
)
520 self
._note
("%s.__bootstrap(): registering profile hook", self
)
521 _sys
.setprofile(_profile_hook
)
527 self
._note
("%s.__bootstrap(): raised SystemExit", self
)
530 self
._note
("%s.__bootstrap(): unhandled exception", self
)
531 # If sys.stderr is no more (most likely from interpreter
532 # shutdown) use self.__stderr. Otherwise still use sys (as in
533 # _sys) in case sys.stderr was redefined since the creation of
536 _sys
.stderr
.write("Exception in thread %s:\n%s\n" %
537 (self
.name
, _format_exc()))
539 # Do the best job possible w/o a huge amt. of code to
540 # approximate a traceback (code ideas from
542 exc_type
, exc_value
, exc_tb
= self
.__exc
_info
()
544 print>>self
.__stderr
, (
545 "Exception in thread " + self
.name
+
546 " (most likely raised during interpreter shutdown):")
547 print>>self
.__stderr
, (
548 "Traceback (most recent call last):")
550 print>>self
.__stderr
, (
551 ' File "%s", line %s, in %s' %
552 (exc_tb
.tb_frame
.f_code
.co_filename
,
554 exc_tb
.tb_frame
.f_code
.co_name
))
555 exc_tb
= exc_tb
.tb_next
556 print>>self
.__stderr
, ("%s: %s" % (exc_type
, exc_value
))
557 # Make sure that exc_tb gets deleted since it is a memory
558 # hog; deleting everything else is just for thoroughness
560 del exc_type
, exc_value
, exc_tb
563 self
._note
("%s.__bootstrap(): normal return", self
)
566 # test_threading.test_no_refcycle_through_target when
567 # the exception keeps the target alive past when we
568 # assert that it's dead.
571 with _active_limbo_lock
:
574 # We don't call self.__delete() because it also
575 # grabs _active_limbo_lock.
576 del _active
[_get_ident()]
581 self
.__block
.acquire()
582 self
.__stopped
= True
583 self
.__block
.notify_all()
584 self
.__block
.release()
587 "Remove current thread from the dict of currently running threads."
589 # Notes about running with dummy_thread:
591 # Must take care to not raise an exception if dummy_thread is being
592 # used (and thus this module is being used as an instance of
593 # dummy_threading). dummy_thread.get_ident() always returns -1 since
594 # there is only one thread if dummy_thread is being used. Thus
595 # len(_active) is always <= 1 here, and any Thread instance created
596 # overwrites the (if any) thread currently registered in _active.
598 # An instance of _MainThread is always created by 'threading'. This
599 # gets overwritten the instant an instance of Thread is created; both
600 # threads return -1 from dummy_thread.get_ident() and thus have the
601 # same key in the dict. So when the _MainThread instance created by
602 # 'threading' tries to clean itself up when atexit calls this method
603 # it gets a KeyError if another Thread instance was created.
605 # This all means that KeyError from trying to delete something from
606 # _active if dummy_threading is being used is a red herring. But
607 # since it isn't if dummy_threading is *not* being used then don't
608 # hide the exception.
611 with _active_limbo_lock
:
612 del _active
[_get_ident()]
613 # There must not be any python code between the previous line
614 # and after the lock is released. Otherwise a tracing function
615 # could try to acquire the lock again in the same thread, (in
616 # current_thread()), and would block.
618 if 'dummy_threading' not in _sys
.modules
:
621 def join(self
, timeout
=None):
622 if not self
.__initialized
:
623 raise RuntimeError("Thread.__init__() not called")
624 if not self
.__started
.is_set():
625 raise RuntimeError("cannot join thread before it is started")
626 if self
is current_thread():
627 raise RuntimeError("cannot join current thread")
630 if not self
.__stopped
:
631 self
._note
("%s.join(): waiting until thread stops", self
)
632 self
.__block
.acquire()
635 while not self
.__stopped
:
638 self
._note
("%s.join(): thread stopped", self
)
640 deadline
= _time() + timeout
641 while not self
.__stopped
:
642 delay
= deadline
- _time()
645 self
._note
("%s.join(): timed out", self
)
647 self
.__block
.wait(delay
)
650 self
._note
("%s.join(): thread stopped", self
)
652 self
.__block
.release()
656 assert self
.__initialized
, "Thread.__init__() not called"
660 def name(self
, name
):
661 assert self
.__initialized
, "Thread.__init__() not called"
662 self
.__name
= str(name
)
666 assert self
.__initialized
, "Thread.__init__() not called"
670 assert self
.__initialized
, "Thread.__init__() not called"
671 return self
.__started
.is_set() and not self
.__stopped
677 assert self
.__initialized
, "Thread.__init__() not called"
678 return self
.__daemonic
681 def daemon(self
, daemonic
):
682 if not self
.__initialized
:
683 raise RuntimeError("Thread.__init__() not called")
684 if self
.__started
.is_set():
685 raise RuntimeError("cannot set daemon status of active thread");
686 self
.__daemonic
= daemonic
691 def setDaemon(self
, daemonic
):
692 self
.daemon
= daemonic
697 def setName(self
, name
):
700 # The timer class was contributed by Itamar Shtull-Trauring
702 def Timer(*args
, **kwargs
):
703 return _Timer(*args
, **kwargs
)
705 class _Timer(Thread
):
706 """Call a function after a specified number of seconds:
708 t = Timer(30.0, f, args=[], kwargs={})
710 t.cancel() # stop the timer's action if it's still waiting
713 def __init__(self
, interval
, function
, args
=[], kwargs
={}):
714 Thread
.__init
__(self
)
715 self
.interval
= interval
716 self
.function
= function
719 self
.finished
= Event()
722 """Stop the timer if it hasn't finished yet"""
726 self
.finished
.wait(self
.interval
)
727 if not self
.finished
.is_set():
728 self
.function(*self
.args
, **self
.kwargs
)
731 # Special thread class to represent the main thread
732 # This is garbage collected through an exit handler
734 class _MainThread(Thread
):
737 Thread
.__init
__(self
, name
="MainThread")
738 self
._Thread
__started
.set()
740 with _active_limbo_lock
:
741 _active
[_get_ident()] = self
743 def _set_daemon(self
):
748 t
= _pickSomeNonDaemonThread()
751 self
._note
("%s: waiting for other threads", self
)
754 t
= _pickSomeNonDaemonThread()
756 self
._note
("%s: exiting", self
)
757 self
._Thread
__delete
()
759 def _pickSomeNonDaemonThread():
760 for t
in enumerate():
761 if not t
.daemon
and t
.is_alive():
766 # Dummy thread class to represent threads not started here.
767 # These aren't garbage collected when they die, nor can they be waited for.
768 # If they invoke anything in threading.py that calls current_thread(), they
769 # leave an entry in the _active dict forever after.
770 # Their purpose is to return *something* from current_thread().
771 # They are marked as daemon threads so we won't wait for them
772 # when we exit (conform previous semantics).
774 class _DummyThread(Thread
):
777 Thread
.__init
__(self
, name
=_newname("Dummy-%d"))
779 # Thread.__block consumes an OS-level locking primitive, which
780 # can never be used by a _DummyThread. Since a _DummyThread
781 # instance is immortal, that's bad, so release this resource.
782 del self
._Thread
__block
784 self
._Thread
__started
.set()
786 with _active_limbo_lock
:
787 _active
[_get_ident()] = self
789 def _set_daemon(self
):
792 def join(self
, timeout
=None):
793 assert False, "cannot join a dummy thread"
796 # Global API functions
800 return _active
[_get_ident()]
802 ##print "current_thread(): no current thread for", _get_ident()
803 return _DummyThread()
805 current_thread
= currentThread
808 with _active_limbo_lock
:
809 return len(_active
) + len(_limbo
)
811 active_count
= activeCount
814 with _active_limbo_lock
:
815 return _active
.values() + _limbo
.values()
817 from thread
import stack_size
819 # Create the main thread object,
820 # and make it available for the interpreter
821 # (Py_Main) as threading._shutdown.
823 _shutdown
= _MainThread()._exitfunc
825 # get thread-local implementation, either from the thread
826 # module, or from the python fallback
829 from thread
import _local
as local
831 from _threading_local
import local
835 # This function is called by Python/ceval.c:PyEval_ReInitThreads which
836 # is called from PyOS_AfterFork. Here we cleanup threading module state
837 # that should not exist after a fork.
839 # Reset _active_limbo_lock, in case we forked while the lock was held
840 # by another (non-forked) thread. http://bugs.python.org/issue874900
841 global _active_limbo_lock
842 _active_limbo_lock
= _allocate_lock()
844 # fork() only copied the current thread; clear references to others.
846 current
= current_thread()
847 with _active_limbo_lock
:
848 for thread
in _active
.itervalues():
849 if thread
is current
:
850 # There is only one active thread. We reset the ident to
851 # its new value since it can have changed.
853 thread
._Thread
__ident
= ident
854 new_active
[ident
] = thread
856 # All the others are already stopped.
857 # We don't call _Thread__stop() because it tries to acquire
858 # thread._Thread__block which could also have been held while
860 thread
._Thread
__stopped
= True
864 _active
.update(new_active
)
865 assert len(_active
) == 1
872 class BoundedQueue(_Verbose
):
874 def __init__(self
, limit
):
875 _Verbose
.__init
__(self
)
877 self
.rc
= Condition(self
.mon
)
878 self
.wc
= Condition(self
.mon
)
884 while len(self
.queue
) >= self
.limit
:
885 self
._note
("put(%s): queue full", item
)
887 self
.queue
.append(item
)
888 self
._note
("put(%s): appended, length now %d",
889 item
, len(self
.queue
))
895 while not self
.queue
:
896 self
._note
("get(): queue empty")
898 item
= self
.queue
.popleft()
899 self
._note
("get(): got %s, %d left", item
, len(self
.queue
))
904 class ProducerThread(Thread
):
906 def __init__(self
, queue
, quota
):
907 Thread
.__init
__(self
, name
="Producer")
912 from random
import random
914 while counter
< self
.quota
:
915 counter
= counter
+ 1
916 self
.queue
.put("%s.%d" % (self
.name
, counter
))
917 _sleep(random() * 0.00001)
920 class ConsumerThread(Thread
):
922 def __init__(self
, queue
, count
):
923 Thread
.__init
__(self
, name
="Consumer")
928 while self
.count
> 0:
929 item
= self
.queue
.get()
931 self
.count
= self
.count
- 1
940 t
= ProducerThread(Q
, NI
)
941 t
.name
= ("Producer-%d" % (i
+1))
943 C
= ConsumerThread(Q
, NI
*NP
)
952 if __name__
== '__main__':