|
rpm-build |
2bd099 |
"""Thread module emulating a subset of Java's threading model."""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
import sys as _sys
|
|
rpm-build |
2bd099 |
import _thread
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
from time import monotonic as _time
|
|
rpm-build |
2bd099 |
from traceback import format_exc as _format_exc
|
|
rpm-build |
2bd099 |
from _weakrefset import WeakSet
|
|
rpm-build |
2bd099 |
from itertools import islice as _islice, count as _count
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
from _collections import deque as _deque
|
|
rpm-build |
2bd099 |
except ImportError:
|
|
rpm-build |
2bd099 |
from collections import deque as _deque
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Note regarding PEP 8 compliant names
|
|
rpm-build |
2bd099 |
# This threading model was originally inspired by Java, and inherited
|
|
rpm-build |
2bd099 |
# the convention of camelCase function and method names from that
|
|
rpm-build |
2bd099 |
# language. Those original names are not in any imminent danger of
|
|
rpm-build |
2bd099 |
# being deprecated (even for Py3k),so this module provides them as an
|
|
rpm-build |
2bd099 |
# alias for the PEP 8 compliant names
|
|
rpm-build |
2bd099 |
# Note that using the new PEP 8 compliant names facilitates substitution
|
|
rpm-build |
2bd099 |
# with the multiprocessing module, which doesn't provide the old
|
|
rpm-build |
2bd099 |
# Java inspired names.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
__all__ = ['get_ident', 'active_count', 'Condition', 'current_thread',
|
|
rpm-build |
2bd099 |
'enumerate', 'main_thread', 'TIMEOUT_MAX',
|
|
rpm-build |
2bd099 |
'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
|
|
rpm-build |
2bd099 |
'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError',
|
|
rpm-build |
2bd099 |
'setprofile', 'settrace', 'local', 'stack_size']
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Rename some stuff so "from threading import *" is safe
|
|
rpm-build |
2bd099 |
_start_new_thread = _thread.start_new_thread
|
|
rpm-build |
2bd099 |
_allocate_lock = _thread.allocate_lock
|
|
rpm-build |
2bd099 |
_set_sentinel = _thread._set_sentinel
|
|
rpm-build |
2bd099 |
get_ident = _thread.get_ident
|
|
rpm-build |
2bd099 |
ThreadError = _thread.error
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
_CRLock = _thread.RLock
|
|
rpm-build |
2bd099 |
except AttributeError:
|
|
rpm-build |
2bd099 |
_CRLock = None
|
|
rpm-build |
2bd099 |
TIMEOUT_MAX = _thread.TIMEOUT_MAX
|
|
rpm-build |
2bd099 |
del _thread
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Support for profile and trace hooks
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
_profile_hook = None
|
|
rpm-build |
2bd099 |
_trace_hook = None
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def setprofile(func):
|
|
rpm-build |
2bd099 |
"""Set a profile function for all threads started from the threading module.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
The func will be passed to sys.setprofile() for each thread, before its
|
|
rpm-build |
2bd099 |
run() method is called.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
global _profile_hook
|
|
rpm-build |
2bd099 |
_profile_hook = func
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def settrace(func):
|
|
rpm-build |
2bd099 |
"""Set a trace function for all threads started from the threading module.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
The func will be passed to sys.settrace() for each thread, before its run()
|
|
rpm-build |
2bd099 |
method is called.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
global _trace_hook
|
|
rpm-build |
2bd099 |
_trace_hook = func
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Synchronization classes
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Lock = _allocate_lock
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def RLock(*args, **kwargs):
|
|
rpm-build |
2bd099 |
"""Factory function that returns a new reentrant lock.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
A reentrant lock must be released by the thread that acquired it. Once a
|
|
rpm-build |
2bd099 |
thread has acquired a reentrant lock, the same thread may acquire it again
|
|
rpm-build |
2bd099 |
without blocking; the thread must release it once for each time it has
|
|
rpm-build |
2bd099 |
acquired it.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if _CRLock is None:
|
|
rpm-build |
2bd099 |
return _PyRLock(*args, **kwargs)
|
|
rpm-build |
2bd099 |
return _CRLock(*args, **kwargs)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class _RLock:
|
|
rpm-build |
2bd099 |
"""This class implements reentrant lock objects.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
A reentrant lock must be released by the thread that acquired it. Once a
|
|
rpm-build |
2bd099 |
thread has acquired a reentrant lock, the same thread may acquire it
|
|
rpm-build |
2bd099 |
again without blocking; the thread must release it once for each time it
|
|
rpm-build |
2bd099 |
has acquired it.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self):
|
|
rpm-build |
2bd099 |
self._block = _allocate_lock()
|
|
rpm-build |
2bd099 |
self._owner = None
|
|
rpm-build |
2bd099 |
self._count = 0
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __repr__(self):
|
|
rpm-build |
2bd099 |
owner = self._owner
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
owner = _active[owner].name
|
|
rpm-build |
2bd099 |
except KeyError:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
return "<%s %s.%s object owner=%r count=%d at %s>" % (
|
|
rpm-build |
2bd099 |
"locked" if self._block.locked() else "unlocked",
|
|
rpm-build |
2bd099 |
self.__class__.__module__,
|
|
rpm-build |
2bd099 |
self.__class__.__qualname__,
|
|
rpm-build |
2bd099 |
owner,
|
|
rpm-build |
2bd099 |
self._count,
|
|
rpm-build |
2bd099 |
hex(id(self))
|
|
rpm-build |
2bd099 |
)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def acquire(self, blocking=True, timeout=-1):
|
|
rpm-build |
2bd099 |
"""Acquire a lock, blocking or non-blocking.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked without arguments: if this thread already owns the lock,
|
|
rpm-build |
2bd099 |
increment the recursion level by one, and return immediately. Otherwise,
|
|
rpm-build |
2bd099 |
if another thread owns the lock, block until the lock is unlocked. Once
|
|
rpm-build |
2bd099 |
the lock is unlocked (not owned by any thread), then grab ownership, set
|
|
rpm-build |
2bd099 |
the recursion level to one, and return. If more than one thread is
|
|
rpm-build |
2bd099 |
blocked waiting until the lock is unlocked, only one at a time will be
|
|
rpm-build |
2bd099 |
able to grab ownership of the lock. There is no return value in this
|
|
rpm-build |
2bd099 |
case.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked with the blocking argument set to true, do the same thing
|
|
rpm-build |
2bd099 |
as when called without arguments, and return true.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked with the blocking argument set to false, do not block. If a
|
|
rpm-build |
2bd099 |
call without an argument would block, return false immediately;
|
|
rpm-build |
2bd099 |
otherwise, do the same thing as when called without arguments, and
|
|
rpm-build |
2bd099 |
return true.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked with the floating-point timeout argument set to a positive
|
|
rpm-build |
2bd099 |
value, block for at most the number of seconds specified by timeout
|
|
rpm-build |
2bd099 |
and as long as the lock cannot be acquired. Return true if the lock has
|
|
rpm-build |
2bd099 |
been acquired, false if the timeout has elapsed.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
me = get_ident()
|
|
rpm-build |
2bd099 |
if self._owner == me:
|
|
rpm-build |
2bd099 |
self._count += 1
|
|
rpm-build |
2bd099 |
return 1
|
|
rpm-build |
2bd099 |
rc = self._block.acquire(blocking, timeout)
|
|
rpm-build |
2bd099 |
if rc:
|
|
rpm-build |
2bd099 |
self._owner = me
|
|
rpm-build |
2bd099 |
self._count = 1
|
|
rpm-build |
2bd099 |
return rc
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
__enter__ = acquire
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def release(self):
|
|
rpm-build |
2bd099 |
"""Release a lock, decrementing the recursion level.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If after the decrement it is zero, reset the lock to unlocked (not owned
|
|
rpm-build |
2bd099 |
by any thread), and if any other threads are blocked waiting for the
|
|
rpm-build |
2bd099 |
lock to become unlocked, allow exactly one of them to proceed. If after
|
|
rpm-build |
2bd099 |
the decrement the recursion level is still nonzero, the lock remains
|
|
rpm-build |
2bd099 |
locked and owned by the calling thread.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Only call this method when the calling thread owns the lock. A
|
|
rpm-build |
2bd099 |
RuntimeError is raised if this method is called when the lock is
|
|
rpm-build |
2bd099 |
unlocked.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
There is no return value.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if self._owner != get_ident():
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot release un-acquired lock")
|
|
rpm-build |
2bd099 |
self._count = count = self._count - 1
|
|
rpm-build |
2bd099 |
if not count:
|
|
rpm-build |
2bd099 |
self._owner = None
|
|
rpm-build |
2bd099 |
self._block.release()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __exit__(self, t, v, tb):
|
|
rpm-build |
2bd099 |
self.release()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Internal methods used by condition variables
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _acquire_restore(self, state):
|
|
rpm-build |
2bd099 |
self._block.acquire()
|
|
rpm-build |
2bd099 |
self._count, self._owner = state
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _release_save(self):
|
|
rpm-build |
2bd099 |
if self._count == 0:
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot release un-acquired lock")
|
|
rpm-build |
2bd099 |
count = self._count
|
|
rpm-build |
2bd099 |
self._count = 0
|
|
rpm-build |
2bd099 |
owner = self._owner
|
|
rpm-build |
2bd099 |
self._owner = None
|
|
rpm-build |
2bd099 |
self._block.release()
|
|
rpm-build |
2bd099 |
return (count, owner)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _is_owned(self):
|
|
rpm-build |
2bd099 |
return self._owner == get_ident()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
_PyRLock = _RLock
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class Condition:
|
|
rpm-build |
2bd099 |
"""Class that implements a condition variable.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
A condition variable allows one or more threads to wait until they are
|
|
rpm-build |
2bd099 |
notified by another thread.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the lock argument is given and not None, it must be a Lock or RLock
|
|
rpm-build |
2bd099 |
object, and it is used as the underlying lock. Otherwise, a new RLock object
|
|
rpm-build |
2bd099 |
is created and used as the underlying lock.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self, lock=None):
|
|
rpm-build |
2bd099 |
if lock is None:
|
|
rpm-build |
2bd099 |
lock = RLock()
|
|
rpm-build |
2bd099 |
self._lock = lock
|
|
rpm-build |
2bd099 |
# Export the lock's acquire() and release() methods
|
|
rpm-build |
2bd099 |
self.acquire = lock.acquire
|
|
rpm-build |
2bd099 |
self.release = lock.release
|
|
rpm-build |
2bd099 |
# If the lock defines _release_save() and/or _acquire_restore(),
|
|
rpm-build |
2bd099 |
# these override the default implementations (which just call
|
|
rpm-build |
2bd099 |
# release() and acquire() on the lock). Ditto for _is_owned().
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self._release_save = lock._release_save
|
|
rpm-build |
2bd099 |
except AttributeError:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self._acquire_restore = lock._acquire_restore
|
|
rpm-build |
2bd099 |
except AttributeError:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self._is_owned = lock._is_owned
|
|
rpm-build |
2bd099 |
except AttributeError:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
self._waiters = _deque()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __enter__(self):
|
|
rpm-build |
2bd099 |
return self._lock.__enter__()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __exit__(self, *args):
|
|
rpm-build |
2bd099 |
return self._lock.__exit__(*args)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __repr__(self):
|
|
rpm-build |
2bd099 |
return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _release_save(self):
|
|
rpm-build |
2bd099 |
self._lock.release() # No state to save
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _acquire_restore(self, x):
|
|
rpm-build |
2bd099 |
self._lock.acquire() # Ignore saved state
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _is_owned(self):
|
|
rpm-build |
2bd099 |
# Return True if lock is owned by current_thread.
|
|
rpm-build |
2bd099 |
# This method is called only if _lock doesn't have _is_owned().
|
|
rpm-build |
2bd099 |
if self._lock.acquire(0):
|
|
rpm-build |
2bd099 |
self._lock.release()
|
|
rpm-build |
2bd099 |
return False
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
return True
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def wait(self, timeout=None):
|
|
rpm-build |
2bd099 |
"""Wait until notified or until a timeout occurs.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the calling thread has not acquired the lock when this method is
|
|
rpm-build |
2bd099 |
called, a RuntimeError is raised.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This method releases the underlying lock, and then blocks until it is
|
|
rpm-build |
2bd099 |
awakened by a notify() or notify_all() call for the same condition
|
|
rpm-build |
2bd099 |
variable in another thread, or until the optional timeout occurs. Once
|
|
rpm-build |
2bd099 |
awakened or timed out, it re-acquires the lock and returns.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the timeout argument is present and not None, it should be a
|
|
rpm-build |
2bd099 |
floating point number specifying a timeout for the operation in seconds
|
|
rpm-build |
2bd099 |
(or fractions thereof).
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the underlying lock is an RLock, it is not released using its
|
|
rpm-build |
2bd099 |
release() method, since this may not actually unlock the lock when it
|
|
rpm-build |
2bd099 |
was acquired multiple times recursively. Instead, an internal interface
|
|
rpm-build |
2bd099 |
of the RLock class is used, which really unlocks it even when it has
|
|
rpm-build |
2bd099 |
been recursively acquired several times. Another internal interface is
|
|
rpm-build |
2bd099 |
then used to restore the recursion level when the lock is reacquired.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if not self._is_owned():
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot wait on un-acquired lock")
|
|
rpm-build |
2bd099 |
waiter = _allocate_lock()
|
|
rpm-build |
2bd099 |
waiter.acquire()
|
|
rpm-build |
2bd099 |
self._waiters.append(waiter)
|
|
rpm-build |
2bd099 |
saved_state = self._release_save()
|
|
rpm-build |
2bd099 |
gotit = False
|
|
rpm-build |
2bd099 |
try: # restore state no matter what (e.g., KeyboardInterrupt)
|
|
rpm-build |
2bd099 |
if timeout is None:
|
|
rpm-build |
2bd099 |
waiter.acquire()
|
|
rpm-build |
2bd099 |
gotit = True
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
if timeout > 0:
|
|
rpm-build |
2bd099 |
gotit = waiter.acquire(True, timeout)
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
gotit = waiter.acquire(False)
|
|
rpm-build |
2bd099 |
return gotit
|
|
rpm-build |
2bd099 |
finally:
|
|
rpm-build |
2bd099 |
self._acquire_restore(saved_state)
|
|
rpm-build |
2bd099 |
if not gotit:
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self._waiters.remove(waiter)
|
|
rpm-build |
2bd099 |
except ValueError:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def wait_for(self, predicate, timeout=None):
|
|
rpm-build |
2bd099 |
"""Wait until a condition evaluates to True.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
predicate should be a callable which result will be interpreted as a
|
|
rpm-build |
2bd099 |
boolean value. A timeout may be provided giving the maximum time to
|
|
rpm-build |
2bd099 |
wait.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
endtime = None
|
|
rpm-build |
2bd099 |
waittime = timeout
|
|
rpm-build |
2bd099 |
result = predicate()
|
|
rpm-build |
2bd099 |
while not result:
|
|
rpm-build |
2bd099 |
if waittime is not None:
|
|
rpm-build |
2bd099 |
if endtime is None:
|
|
rpm-build |
2bd099 |
endtime = _time() + waittime
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
waittime = endtime - _time()
|
|
rpm-build |
2bd099 |
if waittime <= 0:
|
|
rpm-build |
2bd099 |
break
|
|
rpm-build |
2bd099 |
self.wait(waittime)
|
|
rpm-build |
2bd099 |
result = predicate()
|
|
rpm-build |
2bd099 |
return result
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def notify(self, n=1):
|
|
rpm-build |
2bd099 |
"""Wake up one or more threads waiting on this condition, if any.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the calling thread has not acquired the lock when this method is
|
|
rpm-build |
2bd099 |
called, a RuntimeError is raised.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This method wakes up at most n of the threads waiting for the condition
|
|
rpm-build |
2bd099 |
variable; it is a no-op if no threads are waiting.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if not self._is_owned():
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot notify on un-acquired lock")
|
|
rpm-build |
2bd099 |
all_waiters = self._waiters
|
|
rpm-build |
2bd099 |
waiters_to_notify = _deque(_islice(all_waiters, n))
|
|
rpm-build |
2bd099 |
if not waiters_to_notify:
|
|
rpm-build |
2bd099 |
return
|
|
rpm-build |
2bd099 |
for waiter in waiters_to_notify:
|
|
rpm-build |
2bd099 |
waiter.release()
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
all_waiters.remove(waiter)
|
|
rpm-build |
2bd099 |
except ValueError:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def notify_all(self):
|
|
rpm-build |
2bd099 |
"""Wake up all threads waiting on this condition.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the calling thread has not acquired the lock when this method
|
|
rpm-build |
2bd099 |
is called, a RuntimeError is raised.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
self.notify(len(self._waiters))
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
notifyAll = notify_all
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class Semaphore:
|
|
rpm-build |
2bd099 |
"""This class implements semaphore objects.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Semaphores manage a counter representing the number of release() calls minus
|
|
rpm-build |
2bd099 |
the number of acquire() calls, plus an initial value. The acquire() method
|
|
rpm-build |
2bd099 |
blocks if necessary until it can return without making the counter
|
|
rpm-build |
2bd099 |
negative. If not given, value defaults to 1.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# After Tim Peters' semaphore class, but not quite the same (no maximum)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self, value=1):
|
|
rpm-build |
2bd099 |
if value < 0:
|
|
rpm-build |
2bd099 |
raise ValueError("semaphore initial value must be >= 0")
|
|
rpm-build |
2bd099 |
self._cond = Condition(Lock())
|
|
rpm-build |
2bd099 |
self._value = value
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def acquire(self, blocking=True, timeout=None):
|
|
rpm-build |
2bd099 |
"""Acquire a semaphore, decrementing the internal counter by one.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked without arguments: if the internal counter is larger than
|
|
rpm-build |
2bd099 |
zero on entry, decrement it by one and return immediately. If it is zero
|
|
rpm-build |
2bd099 |
on entry, block, waiting until some other thread has called release() to
|
|
rpm-build |
2bd099 |
make it larger than zero. This is done with proper interlocking so that
|
|
rpm-build |
2bd099 |
if multiple acquire() calls are blocked, release() will wake exactly one
|
|
rpm-build |
2bd099 |
of them up. The implementation may pick one at random, so the order in
|
|
rpm-build |
2bd099 |
which blocked threads are awakened should not be relied on. There is no
|
|
rpm-build |
2bd099 |
return value in this case.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked with blocking set to true, do the same thing as when called
|
|
rpm-build |
2bd099 |
without arguments, and return true.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked with blocking set to false, do not block. If a call without
|
|
rpm-build |
2bd099 |
an argument would block, return false immediately; otherwise, do the
|
|
rpm-build |
2bd099 |
same thing as when called without arguments, and return true.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When invoked with a timeout other than None, it will block for at
|
|
rpm-build |
2bd099 |
most timeout seconds. If acquire does not complete successfully in
|
|
rpm-build |
2bd099 |
that interval, return false. Return true otherwise.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if not blocking and timeout is not None:
|
|
rpm-build |
2bd099 |
raise ValueError("can't specify timeout for non-blocking acquire")
|
|
rpm-build |
2bd099 |
rc = False
|
|
rpm-build |
2bd099 |
endtime = None
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
while self._value == 0:
|
|
rpm-build |
2bd099 |
if not blocking:
|
|
rpm-build |
2bd099 |
break
|
|
rpm-build |
2bd099 |
if timeout is not None:
|
|
rpm-build |
2bd099 |
if endtime is None:
|
|
rpm-build |
2bd099 |
endtime = _time() + timeout
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
timeout = endtime - _time()
|
|
rpm-build |
2bd099 |
if timeout <= 0:
|
|
rpm-build |
2bd099 |
break
|
|
rpm-build |
2bd099 |
self._cond.wait(timeout)
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
self._value -= 1
|
|
rpm-build |
2bd099 |
rc = True
|
|
rpm-build |
2bd099 |
return rc
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
__enter__ = acquire
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def release(self):
|
|
rpm-build |
2bd099 |
"""Release a semaphore, incrementing the internal counter by one.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the counter is zero on entry and another thread is waiting for it
|
|
rpm-build |
2bd099 |
to become larger than zero again, wake up that thread.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
self._value += 1
|
|
rpm-build |
2bd099 |
self._cond.notify()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __exit__(self, t, v, tb):
|
|
rpm-build |
2bd099 |
self.release()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class BoundedSemaphore(Semaphore):
|
|
rpm-build |
2bd099 |
"""Implements a bounded semaphore.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
A bounded semaphore checks to make sure its current value doesn't exceed its
|
|
rpm-build |
2bd099 |
initial value. If it does, ValueError is raised. In most situations
|
|
rpm-build |
2bd099 |
semaphores are used to guard resources with limited capacity.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the semaphore is released too many times it's a sign of a bug. If not
|
|
rpm-build |
2bd099 |
given, value defaults to 1.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Like regular semaphores, bounded semaphores manage a counter representing
|
|
rpm-build |
2bd099 |
the number of release() calls minus the number of acquire() calls, plus an
|
|
rpm-build |
2bd099 |
initial value. The acquire() method blocks if necessary until it can return
|
|
rpm-build |
2bd099 |
without making the counter negative. If not given, value defaults to 1.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self, value=1):
|
|
rpm-build |
2bd099 |
Semaphore.__init__(self, value)
|
|
rpm-build |
2bd099 |
self._initial_value = value
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def release(self):
|
|
rpm-build |
2bd099 |
"""Release a semaphore, incrementing the internal counter by one.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the counter is zero on entry and another thread is waiting for it
|
|
rpm-build |
2bd099 |
to become larger than zero again, wake up that thread.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the number of releases exceeds the number of acquires,
|
|
rpm-build |
2bd099 |
raise a ValueError.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
if self._value >= self._initial_value:
|
|
rpm-build |
2bd099 |
raise ValueError("Semaphore released too many times")
|
|
rpm-build |
2bd099 |
self._value += 1
|
|
rpm-build |
2bd099 |
self._cond.notify()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class Event:
|
|
rpm-build |
2bd099 |
"""Class implementing event objects.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Events manage a flag that can be set to true with the set() method and reset
|
|
rpm-build |
2bd099 |
to false with the clear() method. The wait() method blocks until the flag is
|
|
rpm-build |
2bd099 |
true. The flag is initially false.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# After Tim Peters' event class (without is_posted())
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self):
|
|
rpm-build |
2bd099 |
self._cond = Condition(Lock())
|
|
rpm-build |
2bd099 |
self._flag = False
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _reset_internal_locks(self):
|
|
rpm-build |
2bd099 |
# private! called by Thread._reset_internal_locks by _after_fork()
|
|
rpm-build |
2bd099 |
self._cond.__init__(Lock())
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def is_set(self):
|
|
rpm-build |
2bd099 |
"""Return true if and only if the internal flag is true."""
|
|
rpm-build |
2bd099 |
return self._flag
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
isSet = is_set
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def set(self):
|
|
rpm-build |
2bd099 |
"""Set the internal flag to true.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
All threads waiting for it to become true are awakened. Threads
|
|
rpm-build |
2bd099 |
that call wait() once the flag is true will not block at all.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
self._flag = True
|
|
rpm-build |
2bd099 |
self._cond.notify_all()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def clear(self):
|
|
rpm-build |
2bd099 |
"""Reset the internal flag to false.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Subsequently, threads calling wait() will block until set() is called to
|
|
rpm-build |
2bd099 |
set the internal flag to true again.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
self._flag = False
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def wait(self, timeout=None):
|
|
rpm-build |
2bd099 |
"""Block until the internal flag is true.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the internal flag is true on entry, return immediately. Otherwise,
|
|
rpm-build |
2bd099 |
block until another thread calls set() to set the flag to true, or until
|
|
rpm-build |
2bd099 |
the optional timeout occurs.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the timeout argument is present and not None, it should be a
|
|
rpm-build |
2bd099 |
floating point number specifying a timeout for the operation in seconds
|
|
rpm-build |
2bd099 |
(or fractions thereof).
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This method returns the internal flag on exit, so it will always return
|
|
rpm-build |
2bd099 |
True except if a timeout is given and the operation times out.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
signaled = self._flag
|
|
rpm-build |
2bd099 |
if not signaled:
|
|
rpm-build |
2bd099 |
signaled = self._cond.wait(timeout)
|
|
rpm-build |
2bd099 |
return signaled
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# A barrier class. Inspired in part by the pthread_barrier_* api and
|
|
rpm-build |
2bd099 |
# the CyclicBarrier class from Java. See
|
|
rpm-build |
2bd099 |
# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
|
|
rpm-build |
2bd099 |
# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
|
|
rpm-build |
2bd099 |
# CyclicBarrier.html
|
|
rpm-build |
2bd099 |
# for information.
|
|
rpm-build |
2bd099 |
# We maintain two main states, 'filling' and 'draining' enabling the barrier
|
|
rpm-build |
2bd099 |
# to be cyclic. Threads are not allowed into it until it has fully drained
|
|
rpm-build |
2bd099 |
# since the previous cycle. In addition, a 'resetting' state exists which is
|
|
rpm-build |
2bd099 |
# similar to 'draining' except that threads leave with a BrokenBarrierError,
|
|
rpm-build |
2bd099 |
# and a 'broken' state in which all threads get the exception.
|
|
rpm-build |
2bd099 |
class Barrier:
|
|
rpm-build |
2bd099 |
"""Implements a Barrier.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Useful for synchronizing a fixed number of threads at known synchronization
|
|
rpm-build |
2bd099 |
points. Threads block on 'wait()' and are simultaneously once they have all
|
|
rpm-build |
2bd099 |
made that call.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self, parties, action=None, timeout=None):
|
|
rpm-build |
2bd099 |
"""Create a barrier, initialised to 'parties' threads.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
'action' is a callable which, when supplied, will be called by one of
|
|
rpm-build |
2bd099 |
the threads after they have all entered the barrier and just prior to
|
|
rpm-build |
2bd099 |
releasing them all. If a 'timeout' is provided, it is uses as the
|
|
rpm-build |
2bd099 |
default for all subsequent 'wait()' calls.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
self._cond = Condition(Lock())
|
|
rpm-build |
2bd099 |
self._action = action
|
|
rpm-build |
2bd099 |
self._timeout = timeout
|
|
rpm-build |
2bd099 |
self._parties = parties
|
|
rpm-build |
2bd099 |
self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
|
|
rpm-build |
2bd099 |
self._count = 0
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def wait(self, timeout=None):
|
|
rpm-build |
2bd099 |
"""Wait for the barrier.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the specified number of threads have started waiting, they are all
|
|
rpm-build |
2bd099 |
simultaneously awoken. If an 'action' was provided for the barrier, one
|
|
rpm-build |
2bd099 |
of the threads will have executed that callback prior to returning.
|
|
rpm-build |
2bd099 |
Returns an individual index number from 0 to 'parties-1'.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if timeout is None:
|
|
rpm-build |
2bd099 |
timeout = self._timeout
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
self._enter() # Block while the barrier drains.
|
|
rpm-build |
2bd099 |
index = self._count
|
|
rpm-build |
2bd099 |
self._count += 1
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
if index + 1 == self._parties:
|
|
rpm-build |
2bd099 |
# We release the barrier
|
|
rpm-build |
2bd099 |
self._release()
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
# We wait until someone releases us
|
|
rpm-build |
2bd099 |
self._wait(timeout)
|
|
rpm-build |
2bd099 |
return index
|
|
rpm-build |
2bd099 |
finally:
|
|
rpm-build |
2bd099 |
self._count -= 1
|
|
rpm-build |
2bd099 |
# Wake up any threads waiting for barrier to drain.
|
|
rpm-build |
2bd099 |
self._exit()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Block until the barrier is ready for us, or raise an exception
|
|
rpm-build |
2bd099 |
# if it is broken.
|
|
rpm-build |
2bd099 |
def _enter(self):
|
|
rpm-build |
2bd099 |
while self._state in (-1, 1):
|
|
rpm-build |
2bd099 |
# It is draining or resetting, wait until done
|
|
rpm-build |
2bd099 |
self._cond.wait()
|
|
rpm-build |
2bd099 |
#see if the barrier is in a broken state
|
|
rpm-build |
2bd099 |
if self._state < 0:
|
|
rpm-build |
2bd099 |
raise BrokenBarrierError
|
|
rpm-build |
2bd099 |
assert self._state == 0
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Optionally run the 'action' and release the threads waiting
|
|
rpm-build |
2bd099 |
# in the barrier.
|
|
rpm-build |
2bd099 |
def _release(self):
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
if self._action:
|
|
rpm-build |
2bd099 |
self._action()
|
|
rpm-build |
2bd099 |
# enter draining state
|
|
rpm-build |
2bd099 |
self._state = 1
|
|
rpm-build |
2bd099 |
self._cond.notify_all()
|
|
rpm-build |
2bd099 |
except:
|
|
rpm-build |
2bd099 |
#an exception during the _action handler. Break and reraise
|
|
rpm-build |
2bd099 |
self._break()
|
|
rpm-build |
2bd099 |
raise
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Wait in the barrier until we are released. Raise an exception
|
|
rpm-build |
2bd099 |
# if the barrier is reset or broken.
|
|
rpm-build |
2bd099 |
def _wait(self, timeout):
|
|
rpm-build |
2bd099 |
if not self._cond.wait_for(lambda : self._state != 0, timeout):
|
|
rpm-build |
2bd099 |
#timed out. Break the barrier
|
|
rpm-build |
2bd099 |
self._break()
|
|
rpm-build |
2bd099 |
raise BrokenBarrierError
|
|
rpm-build |
2bd099 |
if self._state < 0:
|
|
rpm-build |
2bd099 |
raise BrokenBarrierError
|
|
rpm-build |
2bd099 |
assert self._state == 1
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# If we are the last thread to exit the barrier, signal any threads
|
|
rpm-build |
2bd099 |
# waiting for the barrier to drain.
|
|
rpm-build |
2bd099 |
def _exit(self):
|
|
rpm-build |
2bd099 |
if self._count == 0:
|
|
rpm-build |
2bd099 |
if self._state in (-1, 1):
|
|
rpm-build |
2bd099 |
#resetting or draining
|
|
rpm-build |
2bd099 |
self._state = 0
|
|
rpm-build |
2bd099 |
self._cond.notify_all()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def reset(self):
|
|
rpm-build |
2bd099 |
"""Reset the barrier to the initial state.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Any threads currently waiting will get the BrokenBarrier exception
|
|
rpm-build |
2bd099 |
raised.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
if self._count > 0:
|
|
rpm-build |
2bd099 |
if self._state == 0:
|
|
rpm-build |
2bd099 |
#reset the barrier, waking up threads
|
|
rpm-build |
2bd099 |
self._state = -1
|
|
rpm-build |
2bd099 |
elif self._state == -2:
|
|
rpm-build |
2bd099 |
#was broken, set it to reset state
|
|
rpm-build |
2bd099 |
#which clears when the last thread exits
|
|
rpm-build |
2bd099 |
self._state = -1
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
self._state = 0
|
|
rpm-build |
2bd099 |
self._cond.notify_all()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def abort(self):
|
|
rpm-build |
2bd099 |
"""Place the barrier into a 'broken' state.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
Useful in case of error. Any currently waiting threads and threads
|
|
rpm-build |
2bd099 |
attempting to 'wait()' will have BrokenBarrierError raised.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with self._cond:
|
|
rpm-build |
2bd099 |
self._break()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _break(self):
|
|
rpm-build |
2bd099 |
# An internal error was detected. The barrier is set to
|
|
rpm-build |
2bd099 |
# a broken state all parties awakened.
|
|
rpm-build |
2bd099 |
self._state = -2
|
|
rpm-build |
2bd099 |
self._cond.notify_all()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@property
|
|
rpm-build |
2bd099 |
def parties(self):
|
|
rpm-build |
2bd099 |
"""Return the number of threads required to trip the barrier."""
|
|
rpm-build |
2bd099 |
return self._parties
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@property
|
|
rpm-build |
2bd099 |
def n_waiting(self):
|
|
rpm-build |
2bd099 |
"""Return the number of threads currently waiting at the barrier."""
|
|
rpm-build |
2bd099 |
# We don't need synchronization here since this is an ephemeral result
|
|
rpm-build |
2bd099 |
# anyway. It returns the correct value in the steady state.
|
|
rpm-build |
2bd099 |
if self._state == 0:
|
|
rpm-build |
2bd099 |
return self._count
|
|
rpm-build |
2bd099 |
return 0
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@property
|
|
rpm-build |
2bd099 |
def broken(self):
|
|
rpm-build |
2bd099 |
"""Return True if the barrier is in a broken state."""
|
|
rpm-build |
2bd099 |
return self._state == -2
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# exception raised by the Barrier class
|
|
rpm-build |
2bd099 |
class BrokenBarrierError(RuntimeError):
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Helper to generate new thread names
|
|
rpm-build |
2bd099 |
_counter = _count().__next__
|
|
rpm-build |
2bd099 |
_counter() # Consume 0 so first non-main thread has id 1.
|
|
rpm-build |
2bd099 |
def _newname(template="Thread-%d"):
|
|
rpm-build |
2bd099 |
return template % _counter()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Active thread administration
|
|
rpm-build |
2bd099 |
_active_limbo_lock = _allocate_lock()
|
|
rpm-build |
2bd099 |
_active = {} # maps thread id to Thread object
|
|
rpm-build |
2bd099 |
_limbo = {}
|
|
rpm-build |
2bd099 |
_dangling = WeakSet()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Main class for threads
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class Thread:
|
|
rpm-build |
2bd099 |
"""A class that represents a thread of control.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This class can be safely subclassed in a limited fashion. There are two ways
|
|
rpm-build |
2bd099 |
to specify the activity: by passing a callable object to the constructor, or
|
|
rpm-build |
2bd099 |
by overriding the run() method in a subclass.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
_initialized = False
|
|
rpm-build |
2bd099 |
# Need to store a reference to sys.exc_info for printing
|
|
rpm-build |
2bd099 |
# out exceptions when a thread tries to use a global var. during interp.
|
|
rpm-build |
2bd099 |
# shutdown and thus raises an exception about trying to perform some
|
|
rpm-build |
2bd099 |
# operation on/with a NoneType
|
|
rpm-build |
2bd099 |
_exc_info = _sys.exc_info
|
|
rpm-build |
2bd099 |
# Keep sys.exc_clear too to clear the exception just before
|
|
rpm-build |
2bd099 |
# allowing .join() to return.
|
|
rpm-build |
2bd099 |
#XXX __exc_clear = _sys.exc_clear
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self, group=None, target=None, name=None,
|
|
rpm-build |
2bd099 |
args=(), kwargs=None, *, daemon=None):
|
|
rpm-build |
2bd099 |
"""This constructor should always be called with keyword arguments. Arguments are:
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
*group* should be None; reserved for future extension when a ThreadGroup
|
|
rpm-build |
2bd099 |
class is implemented.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
*target* is the callable object to be invoked by the run()
|
|
rpm-build |
2bd099 |
method. Defaults to None, meaning nothing is called.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
*name* is the thread name. By default, a unique name is constructed of
|
|
rpm-build |
2bd099 |
the form "Thread-N" where N is a small decimal number.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
*args* is the argument tuple for the target invocation. Defaults to ().
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
*kwargs* is a dictionary of keyword arguments for the target
|
|
rpm-build |
2bd099 |
invocation. Defaults to {}.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If a subclass overrides the constructor, it must make sure to invoke
|
|
rpm-build |
2bd099 |
the base class constructor (Thread.__init__()) before doing anything
|
|
rpm-build |
2bd099 |
else to the thread.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
assert group is None, "group argument must be None for now"
|
|
rpm-build |
2bd099 |
if kwargs is None:
|
|
rpm-build |
2bd099 |
kwargs = {}
|
|
rpm-build |
2bd099 |
self._target = target
|
|
rpm-build |
2bd099 |
self._name = str(name or _newname())
|
|
rpm-build |
2bd099 |
self._args = args
|
|
rpm-build |
2bd099 |
self._kwargs = kwargs
|
|
rpm-build |
2bd099 |
if daemon is not None:
|
|
rpm-build |
2bd099 |
self._daemonic = daemon
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
self._daemonic = current_thread().daemon
|
|
rpm-build |
2bd099 |
self._ident = None
|
|
rpm-build |
2bd099 |
self._tstate_lock = None
|
|
rpm-build |
2bd099 |
self._started = Event()
|
|
rpm-build |
2bd099 |
self._is_stopped = False
|
|
rpm-build |
2bd099 |
self._initialized = True
|
|
rpm-build |
2bd099 |
# sys.stderr is not stored in the class like
|
|
rpm-build |
2bd099 |
# sys.exc_info since it can be changed between instances
|
|
rpm-build |
2bd099 |
self._stderr = _sys.stderr
|
|
rpm-build |
2bd099 |
# For debugging and _after_fork()
|
|
rpm-build |
2bd099 |
_dangling.add(self)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _reset_internal_locks(self, is_alive):
|
|
rpm-build |
2bd099 |
# private! Called by _after_fork() to reset our internal locks as
|
|
rpm-build |
2bd099 |
# they may be in an invalid state leading to a deadlock or crash.
|
|
rpm-build |
2bd099 |
self._started._reset_internal_locks()
|
|
rpm-build |
2bd099 |
if is_alive:
|
|
rpm-build |
2bd099 |
self._set_tstate_lock()
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
# The thread isn't alive after fork: it doesn't have a tstate
|
|
rpm-build |
2bd099 |
# anymore.
|
|
rpm-build |
2bd099 |
self._is_stopped = True
|
|
rpm-build |
2bd099 |
self._tstate_lock = None
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __repr__(self):
|
|
rpm-build |
2bd099 |
assert self._initialized, "Thread.__init__() was not called"
|
|
rpm-build |
2bd099 |
status = "initial"
|
|
rpm-build |
2bd099 |
if self._started.is_set():
|
|
rpm-build |
2bd099 |
status = "started"
|
|
rpm-build |
2bd099 |
self.is_alive() # easy way to get ._is_stopped set when appropriate
|
|
rpm-build |
2bd099 |
if self._is_stopped:
|
|
rpm-build |
2bd099 |
status = "stopped"
|
|
rpm-build |
2bd099 |
if self._daemonic:
|
|
rpm-build |
2bd099 |
status += " daemon"
|
|
rpm-build |
2bd099 |
if self._ident is not None:
|
|
rpm-build |
2bd099 |
status += " %s" % self._ident
|
|
rpm-build |
2bd099 |
return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def start(self):
|
|
rpm-build |
2bd099 |
"""Start the thread's activity.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
It must be called at most once per thread object. It arranges for the
|
|
rpm-build |
2bd099 |
object's run() method to be invoked in a separate thread of control.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This method will raise a RuntimeError if called more than once on the
|
|
rpm-build |
2bd099 |
same thread object.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if not self._initialized:
|
|
rpm-build |
2bd099 |
raise RuntimeError("thread.__init__() not called")
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
if self._started.is_set():
|
|
rpm-build |
2bd099 |
raise RuntimeError("threads can only be started once")
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
_limbo[self] = self
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
_start_new_thread(self._bootstrap, ())
|
|
rpm-build |
2bd099 |
except Exception:
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
del _limbo[self]
|
|
rpm-build |
2bd099 |
raise
|
|
rpm-build |
2bd099 |
self._started.wait()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def run(self):
|
|
rpm-build |
2bd099 |
"""Method representing the thread's activity.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
You may override this method in a subclass. The standard run() method
|
|
rpm-build |
2bd099 |
invokes the callable object passed to the object's constructor as the
|
|
rpm-build |
2bd099 |
target argument, if any, with sequential and keyword arguments taken
|
|
rpm-build |
2bd099 |
from the args and kwargs arguments, respectively.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
if self._target:
|
|
rpm-build |
2bd099 |
self._target(*self._args, **self._kwargs)
|
|
rpm-build |
2bd099 |
finally:
|
|
rpm-build |
2bd099 |
# Avoid a refcycle if the thread is running a function with
|
|
rpm-build |
2bd099 |
# an argument that has a member that points to the thread.
|
|
rpm-build |
2bd099 |
del self._target, self._args, self._kwargs
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _bootstrap(self):
|
|
rpm-build |
2bd099 |
# Wrapper around the real bootstrap code that ignores
|
|
rpm-build |
2bd099 |
# exceptions during interpreter cleanup. Those typically
|
|
rpm-build |
2bd099 |
# happen when a daemon thread wakes up at an unfortunate
|
|
rpm-build |
2bd099 |
# moment, finds the world around it destroyed, and raises some
|
|
rpm-build |
2bd099 |
# random exception *** while trying to report the exception in
|
|
rpm-build |
2bd099 |
# _bootstrap_inner() below ***. Those random exceptions
|
|
rpm-build |
2bd099 |
# don't help anybody, and they confuse users, so we suppress
|
|
rpm-build |
2bd099 |
# them. We suppress them only when it appears that the world
|
|
rpm-build |
2bd099 |
# indeed has already been destroyed, so that exceptions in
|
|
rpm-build |
2bd099 |
# _bootstrap_inner() during normal business hours are properly
|
|
rpm-build |
2bd099 |
# reported. Also, we only suppress them for daemonic threads;
|
|
rpm-build |
2bd099 |
# if a non-daemonic encounters this, something else is wrong.
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self._bootstrap_inner()
|
|
rpm-build |
2bd099 |
except:
|
|
rpm-build |
2bd099 |
if self._daemonic and _sys is None:
|
|
rpm-build |
2bd099 |
return
|
|
rpm-build |
2bd099 |
raise
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _set_ident(self):
|
|
rpm-build |
2bd099 |
self._ident = get_ident()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _set_tstate_lock(self):
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
Set a lock object which will be released by the interpreter when
|
|
rpm-build |
2bd099 |
the underlying thread state (see pystate.h) gets deleted.
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
self._tstate_lock = _set_sentinel()
|
|
rpm-build |
2bd099 |
self._tstate_lock.acquire()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _bootstrap_inner(self):
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self._set_ident()
|
|
rpm-build |
2bd099 |
self._set_tstate_lock()
|
|
rpm-build |
2bd099 |
self._started.set()
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
_active[self._ident] = self
|
|
rpm-build |
2bd099 |
del _limbo[self]
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
if _trace_hook:
|
|
rpm-build |
2bd099 |
_sys.settrace(_trace_hook)
|
|
rpm-build |
2bd099 |
if _profile_hook:
|
|
rpm-build |
2bd099 |
_sys.setprofile(_profile_hook)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
self.run()
|
|
rpm-build |
2bd099 |
except SystemExit:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
except:
|
|
rpm-build |
2bd099 |
# If sys.stderr is no more (most likely from interpreter
|
|
rpm-build |
2bd099 |
# shutdown) use self._stderr. Otherwise still use sys (as in
|
|
rpm-build |
2bd099 |
# _sys) in case sys.stderr was redefined since the creation of
|
|
rpm-build |
2bd099 |
# self.
|
|
rpm-build |
2bd099 |
if _sys and _sys.stderr is not None:
|
|
rpm-build |
2bd099 |
print("Exception in thread %s:\n%s" %
|
|
rpm-build |
2bd099 |
(self.name, _format_exc()), file=_sys.stderr)
|
|
rpm-build |
2bd099 |
elif self._stderr is not None:
|
|
rpm-build |
2bd099 |
# Do the best job possible w/o a huge amt. of code to
|
|
rpm-build |
2bd099 |
# approximate a traceback (code ideas from
|
|
rpm-build |
2bd099 |
# Lib/traceback.py)
|
|
rpm-build |
2bd099 |
exc_type, exc_value, exc_tb = self._exc_info()
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
print((
|
|
rpm-build |
2bd099 |
"Exception in thread " + self.name +
|
|
rpm-build |
2bd099 |
" (most likely raised during interpreter shutdown):"), file=self._stderr)
|
|
rpm-build |
2bd099 |
print((
|
|
rpm-build |
2bd099 |
"Traceback (most recent call last):"), file=self._stderr)
|
|
rpm-build |
2bd099 |
while exc_tb:
|
|
rpm-build |
2bd099 |
print((
|
|
rpm-build |
2bd099 |
' File "%s", line %s, in %s' %
|
|
rpm-build |
2bd099 |
(exc_tb.tb_frame.f_code.co_filename,
|
|
rpm-build |
2bd099 |
exc_tb.tb_lineno,
|
|
rpm-build |
2bd099 |
exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
|
|
rpm-build |
2bd099 |
exc_tb = exc_tb.tb_next
|
|
rpm-build |
2bd099 |
print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
|
|
rpm-build |
2bd099 |
# Make sure that exc_tb gets deleted since it is a memory
|
|
rpm-build |
2bd099 |
# hog; deleting everything else is just for thoroughness
|
|
rpm-build |
2bd099 |
finally:
|
|
rpm-build |
2bd099 |
del exc_type, exc_value, exc_tb
|
|
rpm-build |
2bd099 |
finally:
|
|
rpm-build |
2bd099 |
# Prevent a race in
|
|
rpm-build |
2bd099 |
# test_threading.test_no_refcycle_through_target when
|
|
rpm-build |
2bd099 |
# the exception keeps the target alive past when we
|
|
rpm-build |
2bd099 |
# assert that it's dead.
|
|
rpm-build |
2bd099 |
#XXX self._exc_clear()
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
finally:
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
# We don't call self._delete() because it also
|
|
rpm-build |
2bd099 |
# grabs _active_limbo_lock.
|
|
rpm-build |
2bd099 |
del _active[get_ident()]
|
|
rpm-build |
2bd099 |
except:
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _stop(self):
|
|
rpm-build |
2bd099 |
# After calling ._stop(), .is_alive() returns False and .join() returns
|
|
rpm-build |
2bd099 |
# immediately. ._tstate_lock must be released before calling ._stop().
|
|
rpm-build |
2bd099 |
#
|
|
rpm-build |
2bd099 |
# Normal case: C code at the end of the thread's life
|
|
rpm-build |
2bd099 |
# (release_sentinel in _threadmodule.c) releases ._tstate_lock, and
|
|
rpm-build |
2bd099 |
# that's detected by our ._wait_for_tstate_lock(), called by .join()
|
|
rpm-build |
2bd099 |
# and .is_alive(). Any number of threads _may_ call ._stop()
|
|
rpm-build |
2bd099 |
# simultaneously (for example, if multiple threads are blocked in
|
|
rpm-build |
2bd099 |
# .join() calls), and they're not serialized. That's harmless -
|
|
rpm-build |
2bd099 |
# they'll just make redundant rebindings of ._is_stopped and
|
|
rpm-build |
2bd099 |
# ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the
|
|
rpm-build |
2bd099 |
# "assert self._is_stopped" in ._wait_for_tstate_lock() always works
|
|
rpm-build |
2bd099 |
# (the assert is executed only if ._tstate_lock is None).
|
|
rpm-build |
2bd099 |
#
|
|
rpm-build |
2bd099 |
# Special case: _main_thread releases ._tstate_lock via this
|
|
rpm-build |
2bd099 |
# module's _shutdown() function.
|
|
rpm-build |
2bd099 |
lock = self._tstate_lock
|
|
rpm-build |
2bd099 |
if lock is not None:
|
|
rpm-build |
2bd099 |
assert not lock.locked()
|
|
rpm-build |
2bd099 |
self._is_stopped = True
|
|
rpm-build |
2bd099 |
self._tstate_lock = None
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _delete(self):
|
|
rpm-build |
2bd099 |
"Remove current thread from the dict of currently running threads."
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Notes about running with _dummy_thread:
|
|
rpm-build |
2bd099 |
#
|
|
rpm-build |
2bd099 |
# Must take care to not raise an exception if _dummy_thread is being
|
|
rpm-build |
2bd099 |
# used (and thus this module is being used as an instance of
|
|
rpm-build |
2bd099 |
# dummy_threading). _dummy_thread.get_ident() always returns -1 since
|
|
rpm-build |
2bd099 |
# there is only one thread if _dummy_thread is being used. Thus
|
|
rpm-build |
2bd099 |
# len(_active) is always <= 1 here, and any Thread instance created
|
|
rpm-build |
2bd099 |
# overwrites the (if any) thread currently registered in _active.
|
|
rpm-build |
2bd099 |
#
|
|
rpm-build |
2bd099 |
# An instance of _MainThread is always created by 'threading'. This
|
|
rpm-build |
2bd099 |
# gets overwritten the instant an instance of Thread is created; both
|
|
rpm-build |
2bd099 |
# threads return -1 from _dummy_thread.get_ident() and thus have the
|
|
rpm-build |
2bd099 |
# same key in the dict. So when the _MainThread instance created by
|
|
rpm-build |
2bd099 |
# 'threading' tries to clean itself up when atexit calls this method
|
|
rpm-build |
2bd099 |
# it gets a KeyError if another Thread instance was created.
|
|
rpm-build |
2bd099 |
#
|
|
rpm-build |
2bd099 |
# This all means that KeyError from trying to delete something from
|
|
rpm-build |
2bd099 |
# _active if dummy_threading is being used is a red herring. But
|
|
rpm-build |
2bd099 |
# since it isn't if dummy_threading is *not* being used then don't
|
|
rpm-build |
2bd099 |
# hide the exception.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
del _active[get_ident()]
|
|
rpm-build |
2bd099 |
# There must not be any python code between the previous line
|
|
rpm-build |
2bd099 |
# and after the lock is released. Otherwise a tracing function
|
|
rpm-build |
2bd099 |
# could try to acquire the lock again in the same thread, (in
|
|
rpm-build |
2bd099 |
# current_thread()), and would block.
|
|
rpm-build |
2bd099 |
except KeyError:
|
|
rpm-build |
2bd099 |
if 'dummy_threading' not in _sys.modules:
|
|
rpm-build |
2bd099 |
raise
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def join(self, timeout=None):
|
|
rpm-build |
2bd099 |
"""Wait until the thread terminates.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This blocks the calling thread until the thread whose join() method is
|
|
rpm-build |
2bd099 |
called terminates -- either normally or through an unhandled exception
|
|
rpm-build |
2bd099 |
or until the optional timeout occurs.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the timeout argument is present and not None, it should be a
|
|
rpm-build |
2bd099 |
floating point number specifying a timeout for the operation in seconds
|
|
rpm-build |
2bd099 |
(or fractions thereof). As join() always returns None, you must call
|
|
rpm-build |
2bd099 |
isAlive() after join() to decide whether a timeout happened -- if the
|
|
rpm-build |
2bd099 |
thread is still alive, the join() call timed out.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
When the timeout argument is not present or None, the operation will
|
|
rpm-build |
2bd099 |
block until the thread terminates.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
A thread can be join()ed many times.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
join() raises a RuntimeError if an attempt is made to join the current
|
|
rpm-build |
2bd099 |
thread as that would cause a deadlock. It is also an error to join() a
|
|
rpm-build |
2bd099 |
thread before it has been started and attempts to do so raises the same
|
|
rpm-build |
2bd099 |
exception.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
if not self._initialized:
|
|
rpm-build |
2bd099 |
raise RuntimeError("Thread.__init__() not called")
|
|
rpm-build |
2bd099 |
if not self._started.is_set():
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot join thread before it is started")
|
|
rpm-build |
2bd099 |
if self is current_thread():
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot join current thread")
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
if timeout is None:
|
|
rpm-build |
2bd099 |
self._wait_for_tstate_lock()
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
# the behavior of a negative timeout isn't documented, but
|
|
rpm-build |
2bd099 |
# historically .join(timeout=x) for x<0 has acted as if timeout=0
|
|
rpm-build |
2bd099 |
self._wait_for_tstate_lock(timeout=max(timeout, 0))
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _wait_for_tstate_lock(self, block=True, timeout=-1):
|
|
rpm-build |
2bd099 |
# Issue #18808: wait for the thread state to be gone.
|
|
rpm-build |
2bd099 |
# At the end of the thread's life, after all knowledge of the thread
|
|
rpm-build |
2bd099 |
# is removed from C data structures, C code releases our _tstate_lock.
|
|
rpm-build |
2bd099 |
# This method passes its arguments to _tstate_lock.acquire().
|
|
rpm-build |
2bd099 |
# If the lock is acquired, the C code is done, and self._stop() is
|
|
rpm-build |
2bd099 |
# called. That sets ._is_stopped to True, and ._tstate_lock to None.
|
|
rpm-build |
2bd099 |
lock = self._tstate_lock
|
|
rpm-build |
2bd099 |
if lock is None: # already determined that the C code is done
|
|
rpm-build |
2bd099 |
assert self._is_stopped
|
|
rpm-build |
2bd099 |
elif lock.acquire(block, timeout):
|
|
rpm-build |
2bd099 |
lock.release()
|
|
rpm-build |
2bd099 |
self._stop()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@property
|
|
rpm-build |
2bd099 |
def name(self):
|
|
rpm-build |
2bd099 |
"""A string used for identification purposes only.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
It has no semantics. Multiple threads may be given the same name. The
|
|
rpm-build |
2bd099 |
initial name is set by the constructor.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
assert self._initialized, "Thread.__init__() not called"
|
|
rpm-build |
2bd099 |
return self._name
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@name.setter
|
|
rpm-build |
2bd099 |
def name(self, name):
|
|
rpm-build |
2bd099 |
assert self._initialized, "Thread.__init__() not called"
|
|
rpm-build |
2bd099 |
self._name = str(name)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@property
|
|
rpm-build |
2bd099 |
def ident(self):
|
|
rpm-build |
2bd099 |
"""Thread identifier of this thread or None if it has not been started.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This is a nonzero integer. See the thread.get_ident() function. Thread
|
|
rpm-build |
2bd099 |
identifiers may be recycled when a thread exits and another thread is
|
|
rpm-build |
2bd099 |
created. The identifier is available even after the thread has exited.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
assert self._initialized, "Thread.__init__() not called"
|
|
rpm-build |
2bd099 |
return self._ident
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def is_alive(self):
|
|
rpm-build |
2bd099 |
"""Return whether the thread is alive.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This method returns True just before the run() method starts until just
|
|
rpm-build |
2bd099 |
after the run() method terminates. The module function enumerate()
|
|
rpm-build |
2bd099 |
returns a list of all alive threads.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
assert self._initialized, "Thread.__init__() not called"
|
|
rpm-build |
2bd099 |
if self._is_stopped or not self._started.is_set():
|
|
rpm-build |
2bd099 |
return False
|
|
rpm-build |
2bd099 |
self._wait_for_tstate_lock(False)
|
|
rpm-build |
2bd099 |
return not self._is_stopped
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
isAlive = is_alive
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@property
|
|
rpm-build |
2bd099 |
def daemon(self):
|
|
rpm-build |
2bd099 |
"""A boolean value indicating whether this thread is a daemon thread.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
This must be set before start() is called, otherwise RuntimeError is
|
|
rpm-build |
2bd099 |
raised. Its initial value is inherited from the creating thread; the
|
|
rpm-build |
2bd099 |
main thread is not a daemon thread and therefore all threads created in
|
|
rpm-build |
2bd099 |
the main thread default to daemon = False.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
The entire Python program exits when no alive non-daemon threads are
|
|
rpm-build |
2bd099 |
left.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
assert self._initialized, "Thread.__init__() not called"
|
|
rpm-build |
2bd099 |
return self._daemonic
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
@daemon.setter
|
|
rpm-build |
2bd099 |
def daemon(self, daemonic):
|
|
rpm-build |
2bd099 |
if not self._initialized:
|
|
rpm-build |
2bd099 |
raise RuntimeError("Thread.__init__() not called")
|
|
rpm-build |
2bd099 |
if self._started.is_set():
|
|
rpm-build |
2bd099 |
raise RuntimeError("cannot set daemon status of active thread")
|
|
rpm-build |
2bd099 |
self._daemonic = daemonic
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def isDaemon(self):
|
|
rpm-build |
2bd099 |
return self.daemon
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def setDaemon(self, daemonic):
|
|
rpm-build |
2bd099 |
self.daemon = daemonic
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def getName(self):
|
|
rpm-build |
2bd099 |
return self.name
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def setName(self, name):
|
|
rpm-build |
2bd099 |
self.name = name
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# The timer class was contributed by Itamar Shtull-Trauring
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class Timer(Thread):
|
|
rpm-build |
2bd099 |
"""Call a function after a specified number of seconds:
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
t = Timer(30.0, f, args=None, kwargs=None)
|
|
rpm-build |
2bd099 |
t.start()
|
|
rpm-build |
2bd099 |
t.cancel() # stop the timer's action if it's still waiting
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self, interval, function, args=None, kwargs=None):
|
|
rpm-build |
2bd099 |
Thread.__init__(self)
|
|
rpm-build |
2bd099 |
self.interval = interval
|
|
rpm-build |
2bd099 |
self.function = function
|
|
rpm-build |
2bd099 |
self.args = args if args is not None else []
|
|
rpm-build |
2bd099 |
self.kwargs = kwargs if kwargs is not None else {}
|
|
rpm-build |
2bd099 |
self.finished = Event()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def cancel(self):
|
|
rpm-build |
2bd099 |
"""Stop the timer if it hasn't finished yet."""
|
|
rpm-build |
2bd099 |
self.finished.set()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def run(self):
|
|
rpm-build |
2bd099 |
self.finished.wait(self.interval)
|
|
rpm-build |
2bd099 |
if not self.finished.is_set():
|
|
rpm-build |
2bd099 |
self.function(*self.args, **self.kwargs)
|
|
rpm-build |
2bd099 |
self.finished.set()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Special thread class to represent the main thread
|
|
rpm-build |
2bd099 |
# This is garbage collected through an exit handler
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class _MainThread(Thread):
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self):
|
|
rpm-build |
2bd099 |
Thread.__init__(self, name="MainThread", daemon=False)
|
|
rpm-build |
2bd099 |
self._set_tstate_lock()
|
|
rpm-build |
2bd099 |
self._started.set()
|
|
rpm-build |
2bd099 |
self._set_ident()
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
_active[self._ident] = self
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Dummy thread class to represent threads not started here.
|
|
rpm-build |
2bd099 |
# These aren't garbage collected when they die, nor can they be waited for.
|
|
rpm-build |
2bd099 |
# If they invoke anything in threading.py that calls current_thread(), they
|
|
rpm-build |
2bd099 |
# leave an entry in the _active dict forever after.
|
|
rpm-build |
2bd099 |
# Their purpose is to return *something* from current_thread().
|
|
rpm-build |
2bd099 |
# They are marked as daemon threads so we won't wait for them
|
|
rpm-build |
2bd099 |
# when we exit (conform previous semantics).
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
class _DummyThread(Thread):
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def __init__(self):
|
|
rpm-build |
2bd099 |
Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
self._started.set()
|
|
rpm-build |
2bd099 |
self._set_ident()
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
_active[self._ident] = self
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _stop(self):
|
|
rpm-build |
2bd099 |
pass
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def is_alive(self):
|
|
rpm-build |
2bd099 |
assert not self._is_stopped and self._started.is_set()
|
|
rpm-build |
2bd099 |
return True
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def join(self, timeout=None):
|
|
rpm-build |
2bd099 |
assert False, "cannot join a dummy thread"
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Global API functions
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def current_thread():
|
|
rpm-build |
2bd099 |
"""Return the current Thread object, corresponding to the caller's thread of control.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
If the caller's thread of control was not created through the threading
|
|
rpm-build |
2bd099 |
module, a dummy thread object with limited functionality is returned.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
return _active[get_ident()]
|
|
rpm-build |
2bd099 |
except KeyError:
|
|
rpm-build |
2bd099 |
return _DummyThread()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
currentThread = current_thread
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def active_count():
|
|
rpm-build |
2bd099 |
"""Return the number of Thread objects currently alive.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
The returned count is equal to the length of the list returned by
|
|
rpm-build |
2bd099 |
enumerate().
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
return len(_active) + len(_limbo)
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
activeCount = active_count
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _enumerate():
|
|
rpm-build |
2bd099 |
# Same as enumerate(), but without the lock. Internal use only.
|
|
rpm-build |
2bd099 |
return list(_active.values()) + list(_limbo.values())
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def enumerate():
|
|
rpm-build |
2bd099 |
"""Return a list of all Thread objects currently alive.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
The list includes daemonic threads, dummy thread objects created by
|
|
rpm-build |
2bd099 |
current_thread(), and the main thread. It excludes terminated threads and
|
|
rpm-build |
2bd099 |
threads that have not yet been started.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
return list(_active.values()) + list(_limbo.values())
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
from _thread import stack_size
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Create the main thread object,
|
|
rpm-build |
2bd099 |
# and make it available for the interpreter
|
|
rpm-build |
2bd099 |
# (Py_Main) as threading._shutdown.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
_main_thread = _MainThread()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _shutdown():
|
|
rpm-build |
2bd099 |
# Obscure: other threads may be waiting to join _main_thread. That's
|
|
rpm-build |
2bd099 |
# dubious, but some code does it. We can't wait for C code to release
|
|
rpm-build |
2bd099 |
# the main thread's tstate_lock - that won't happen until the interpreter
|
|
rpm-build |
2bd099 |
# is nearly dead. So we release it here. Note that just calling _stop()
|
|
rpm-build |
2bd099 |
# isn't enough: other threads may already be waiting on _tstate_lock.
|
|
rpm-build |
2bd099 |
tlock = _main_thread._tstate_lock
|
|
rpm-build |
2bd099 |
# The main thread isn't finished yet, so its thread state lock can't have
|
|
rpm-build |
2bd099 |
# been released.
|
|
rpm-build |
2bd099 |
assert tlock is not None
|
|
rpm-build |
2bd099 |
assert tlock.locked()
|
|
rpm-build |
2bd099 |
tlock.release()
|
|
rpm-build |
2bd099 |
_main_thread._stop()
|
|
rpm-build |
2bd099 |
t = _pickSomeNonDaemonThread()
|
|
rpm-build |
2bd099 |
while t:
|
|
rpm-build |
2bd099 |
t.join()
|
|
rpm-build |
2bd099 |
t = _pickSomeNonDaemonThread()
|
|
rpm-build |
2bd099 |
_main_thread._delete()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _pickSomeNonDaemonThread():
|
|
rpm-build |
2bd099 |
for t in enumerate():
|
|
rpm-build |
2bd099 |
if not t.daemon and t.is_alive():
|
|
rpm-build |
2bd099 |
return t
|
|
rpm-build |
2bd099 |
return None
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def main_thread():
|
|
rpm-build |
2bd099 |
"""Return the main thread object.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
In normal conditions, the main thread is the thread from which the
|
|
rpm-build |
2bd099 |
Python interpreter was started.
|
|
rpm-build |
2bd099 |
"""
|
|
rpm-build |
2bd099 |
return _main_thread
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# get thread-local implementation, either from the thread
|
|
rpm-build |
2bd099 |
# module, or from the python fallback
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
try:
|
|
rpm-build |
2bd099 |
from _thread import _local as local
|
|
rpm-build |
2bd099 |
except ImportError:
|
|
rpm-build |
2bd099 |
from _threading_local import local
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
def _after_fork():
|
|
rpm-build |
2bd099 |
# This function is called by Python/ceval.c:PyEval_ReInitThreads which
|
|
rpm-build |
2bd099 |
# is called from PyOS_AfterFork. Here we cleanup threading module state
|
|
rpm-build |
2bd099 |
# that should not exist after a fork.
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# Reset _active_limbo_lock, in case we forked while the lock was held
|
|
rpm-build |
2bd099 |
# by another (non-forked) thread. http://bugs.python.org/issue874900
|
|
rpm-build |
2bd099 |
global _active_limbo_lock, _main_thread
|
|
rpm-build |
2bd099 |
_active_limbo_lock = _allocate_lock()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
# fork() only copied the current thread; clear references to others.
|
|
rpm-build |
2bd099 |
new_active = {}
|
|
rpm-build |
2bd099 |
current = current_thread()
|
|
rpm-build |
2bd099 |
_main_thread = current
|
|
rpm-build |
2bd099 |
with _active_limbo_lock:
|
|
rpm-build |
2bd099 |
# Dangling thread instances must still have their locks reset,
|
|
rpm-build |
2bd099 |
# because someone may join() them.
|
|
rpm-build |
2bd099 |
threads = set(_enumerate())
|
|
rpm-build |
2bd099 |
threads.update(_dangling)
|
|
rpm-build |
2bd099 |
for thread in threads:
|
|
rpm-build |
2bd099 |
# Any lock/condition variable may be currently locked or in an
|
|
rpm-build |
2bd099 |
# invalid state, so we reinitialize them.
|
|
rpm-build |
2bd099 |
if thread is current:
|
|
rpm-build |
2bd099 |
# There is only one active thread. We reset the ident to
|
|
rpm-build |
2bd099 |
# its new value since it can have changed.
|
|
rpm-build |
2bd099 |
thread._reset_internal_locks(True)
|
|
rpm-build |
2bd099 |
ident = get_ident()
|
|
rpm-build |
2bd099 |
thread._ident = ident
|
|
rpm-build |
2bd099 |
new_active[ident] = thread
|
|
rpm-build |
2bd099 |
else:
|
|
rpm-build |
2bd099 |
# All the others are already stopped.
|
|
rpm-build |
2bd099 |
thread._reset_internal_locks(False)
|
|
rpm-build |
2bd099 |
thread._stop()
|
|
rpm-build |
2bd099 |
|
|
rpm-build |
2bd099 |
_limbo.clear()
|
|
rpm-build |
2bd099 |
_active.clear()
|
|
rpm-build |
2bd099 |
_active.update(new_active)
|
|
rpm-build |
2bd099 |
assert len(_active) == 1
|