同步操作将从 OpenHarmony-SIG/python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
"""Thread module emulating a subset of Java's threading model."""import os as _osimport sys as _sysimport _threadfrom time import monotonic as _timefrom _weakrefset import WeakSetfrom itertools import islice as _islice, count as _counttry:from _collections import deque as _dequeexcept ImportError:from collections import deque as _deque# Note regarding PEP 8 compliant names# This threading model was originally inspired by Java, and inherited# the convention of camelCase function and method names from that# language. Those original names are not in any imminent danger of# being deprecated (even for Py3k),so this module provides them as an# alias for the PEP 8 compliant names# Note that using the new PEP 8 compliant names facilitates substitution# with the multiprocessing module, which doesn't provide the old# Java inspired names.__all__ = ['get_ident', 'active_count', 'Condition', 'current_thread','enumerate', 'main_thread', 'TIMEOUT_MAX','Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread','Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError','setprofile', 'settrace', 'local', 'stack_size','excepthook', 'ExceptHookArgs']# Rename some stuff so "from threading import *" is safe_start_new_thread = _thread.start_new_thread_allocate_lock = _thread.allocate_lock_set_sentinel = _thread._set_sentinelget_ident = _thread.get_identtry:get_native_id = _thread.get_native_id_HAVE_THREAD_NATIVE_ID = True__all__.append('get_native_id')except AttributeError:_HAVE_THREAD_NATIVE_ID = FalseThreadError = _thread.errortry:_CRLock = _thread.RLockexcept AttributeError:_CRLock = NoneTIMEOUT_MAX = _thread.TIMEOUT_MAXdel _thread# Support for profile and trace hooks_profile_hook = None_trace_hook = Nonedef setprofile(func):"""Set a profile function for all threads started from the threading module.The func will be passed to sys.setprofile() for each thread, before itsrun() method is called."""global _profile_hook_profile_hook = funcdef settrace(func):"""Set a trace function for all threads started from the threading module.The func will be passed to sys.settrace() for each thread, before its run()method is called."""global _trace_hook_trace_hook = func# Synchronization classesLock = _allocate_lockdef RLock(*args, **kwargs):"""Factory function that returns a new reentrant lock.A reentrant lock must be released by the thread that acquired it. Once athread has acquired a reentrant lock, the same thread may acquire it againwithout blocking; the thread must release it once for each time it hasacquired it."""if _CRLock is None:return _PyRLock(*args, **kwargs)return _CRLock(*args, **kwargs)class _RLock:"""This class implements reentrant lock objects.A reentrant lock must be released by the thread that acquired it. Once athread has acquired a reentrant lock, the same thread may acquire itagain without blocking; the thread must release it once for each time ithas acquired it."""def __init__(self):self._block = _allocate_lock()self._owner = Noneself._count = 0def __repr__(self):owner = self._ownertry:owner = _active[owner].nameexcept KeyError:passreturn "<%s %s.%s object owner=%r count=%d at %s>" % ("locked" if self._block.locked() else "unlocked",self.__class__.__module__,self.__class__.__qualname__,owner,self._count,hex(id(self)))def acquire(self, blocking=True, timeout=-1):"""Acquire a lock, blocking or non-blocking.When invoked without arguments: if this thread already owns the lock,increment the recursion level by one, and return immediately. Otherwise,if another thread owns the lock, block until the lock is unlocked. Oncethe lock is unlocked (not owned by any thread), then grab ownership, setthe recursion level to one, and return. If more than one thread isblocked waiting until the lock is unlocked, only one at a time will beable to grab ownership of the lock. There is no return value in thiscase.When invoked with the blocking argument set to true, do the same thingas when called without arguments, and return true.When invoked with the blocking argument set to false, do not block. If acall without an argument would block, return false immediately;otherwise, do the same thing as when called without arguments, andreturn true.When invoked with the floating-point timeout argument set to a positivevalue, block for at most the number of seconds specified by timeoutand as long as the lock cannot be acquired. Return true if the lock hasbeen acquired, false if the timeout has elapsed."""me = get_ident()if self._owner == me:self._count += 1return 1rc = self._block.acquire(blocking, timeout)if rc:self._owner = meself._count = 1return rc__enter__ = acquiredef release(self):"""Release a lock, decrementing the recursion level.If after the decrement it is zero, reset the lock to unlocked (not ownedby any thread), and if any other threads are blocked waiting for thelock to become unlocked, allow exactly one of them to proceed. If afterthe decrement the recursion level is still nonzero, the lock remainslocked and owned by the calling thread.Only call this method when the calling thread owns the lock. ARuntimeError is raised if this method is called when the lock isunlocked.There is no return value."""if self._owner != get_ident():raise RuntimeError("cannot release un-acquired lock")self._count = count = self._count - 1if not count:self._owner = Noneself._block.release()def __exit__(self, t, v, tb):self.release()# Internal methods used by condition variablesdef _acquire_restore(self, state):self._block.acquire()self._count, self._owner = statedef _release_save(self):if self._count == 0:raise RuntimeError("cannot release un-acquired lock")count = self._countself._count = 0owner = self._ownerself._owner = Noneself._block.release()return (count, owner)def _is_owned(self):return self._owner == get_ident()_PyRLock = _RLockclass Condition:"""Class that implements a condition variable.A condition variable allows one or more threads to wait until they arenotified by another thread.If the lock argument is given and not None, it must be a Lock or RLockobject, and it is used as the underlying lock. Otherwise, a new RLock objectis created and used as the underlying lock."""def __init__(self, lock=None):if lock is None:lock = RLock()self._lock = lock# Export the lock's acquire() and release() methodsself.acquire = lock.acquireself.release = lock.release# If the lock defines _release_save() and/or _acquire_restore(),# these override the default implementations (which just call# release() and acquire() on the lock). Ditto for _is_owned().try:self._release_save = lock._release_saveexcept AttributeError:passtry:self._acquire_restore = lock._acquire_restoreexcept AttributeError:passtry:self._is_owned = lock._is_ownedexcept AttributeError:passself._waiters = _deque()def __enter__(self):return self._lock.__enter__()def __exit__(self, *args):return self._lock.__exit__(*args)def __repr__(self):return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))def _release_save(self):self._lock.release() # No state to savedef _acquire_restore(self, x):self._lock.acquire() # Ignore saved statedef _is_owned(self):# Return True if lock is owned by current_thread.# This method is called only if _lock doesn't have _is_owned().if self._lock.acquire(0):self._lock.release()return Falseelse:return Truedef wait(self, timeout=None):"""Wait until notified or until a timeout occurs.If the calling thread has not acquired the lock when this method iscalled, a RuntimeError is raised.This method releases the underlying lock, and then blocks until it isawakened by a notify() or notify_all() call for the same conditionvariable in another thread, or until the optional timeout occurs. Onceawakened or timed out, it re-acquires the lock and returns.When the timeout argument is present and not None, it should be afloating point number specifying a timeout for the operation in seconds(or fractions thereof).When the underlying lock is an RLock, it is not released using itsrelease() method, since this may not actually unlock the lock when itwas acquired multiple times recursively. Instead, an internal interfaceof the RLock class is used, which really unlocks it even when it hasbeen recursively acquired several times. Another internal interface isthen used to restore the recursion level when the lock is reacquired."""if not self._is_owned():raise RuntimeError("cannot wait on un-acquired lock")waiter = _allocate_lock()waiter.acquire()self._waiters.append(waiter)saved_state = self._release_save()gotit = Falsetry: # restore state no matter what (e.g., KeyboardInterrupt)if timeout is None:waiter.acquire()gotit = Trueelse:if timeout > 0:gotit = waiter.acquire(True, timeout)else:gotit = waiter.acquire(False)return gotitfinally:self._acquire_restore(saved_state)if not gotit:try:self._waiters.remove(waiter)except ValueError:passdef wait_for(self, predicate, timeout=None):"""Wait until a condition evaluates to True.predicate should be a callable which result will be interpreted as aboolean value. A timeout may be provided giving the maximum time towait."""endtime = Nonewaittime = timeoutresult = predicate()while not result:if waittime is not None:if endtime is None:endtime = _time() + waittimeelse:waittime = endtime - _time()if waittime <= 0:breakself.wait(waittime)result = predicate()return resultdef notify(self, n=1):"""Wake up one or more threads waiting on this condition, if any.If the calling thread has not acquired the lock when this method iscalled, a RuntimeError is raised.This method wakes up at most n of the threads waiting for the conditionvariable; it is a no-op if no threads are waiting."""if not self._is_owned():raise RuntimeError("cannot notify on un-acquired lock")all_waiters = self._waiterswaiters_to_notify = _deque(_islice(all_waiters, n))if not waiters_to_notify:returnfor waiter in waiters_to_notify:waiter.release()try:all_waiters.remove(waiter)except ValueError:passdef notify_all(self):"""Wake up all threads waiting on this condition.If the calling thread has not acquired the lock when this methodis called, a RuntimeError is raised."""self.notify(len(self._waiters))notifyAll = notify_allclass Semaphore:"""This class implements semaphore objects.Semaphores manage a counter representing the number of release() calls minusthe number of acquire() calls, plus an initial value. The acquire() methodblocks if necessary until it can return without making the counternegative. If not given, value defaults to 1."""# After Tim Peters' semaphore class, but not quite the same (no maximum)def __init__(self, value=1):if value < 0:raise ValueError("semaphore initial value must be >= 0")self._cond = Condition(Lock())self._value = valuedef acquire(self, blocking=True, timeout=None):"""Acquire a semaphore, decrementing the internal counter by one.When invoked without arguments: if the internal counter is larger thanzero on entry, decrement it by one and return immediately. If it is zeroon entry, block, waiting until some other thread has called release() tomake it larger than zero. This is done with proper interlocking so thatif multiple acquire() calls are blocked, release() will wake exactly oneof them up. The implementation may pick one at random, so the order inwhich blocked threads are awakened should not be relied on. There is noreturn value in this case.When invoked with blocking set to true, do the same thing as when calledwithout arguments, and return true.When invoked with blocking set to false, do not block. If a call withoutan argument would block, return false immediately; otherwise, do thesame thing as when called without arguments, and return true.When invoked with a timeout other than None, it will block for atmost timeout seconds. If acquire does not complete successfully inthat interval, return false. Return true otherwise."""if not blocking and timeout is not None:raise ValueError("can't specify timeout for non-blocking acquire")rc = Falseendtime = Nonewith self._cond:while self._value == 0:if not blocking:breakif timeout is not None:if endtime is None:endtime = _time() + timeoutelse:timeout = endtime - _time()if timeout <= 0:breakself._cond.wait(timeout)else:self._value -= 1rc = Truereturn rc__enter__ = acquiredef release(self):"""Release a semaphore, incrementing the internal counter by one.When the counter is zero on entry and another thread is waiting for itto become larger than zero again, wake up that thread."""with self._cond:self._value += 1self._cond.notify()def __exit__(self, t, v, tb):self.release()class BoundedSemaphore(Semaphore):"""Implements a bounded semaphore.A bounded semaphore checks to make sure its current value doesn't exceed itsinitial value. If it does, ValueError is raised. In most situationssemaphores are used to guard resources with limited capacity.If the semaphore is released too many times it's a sign of a bug. If notgiven, value defaults to 1.Like regular semaphores, bounded semaphores manage a counter representingthe number of release() calls minus the number of acquire() calls, plus aninitial value. The acquire() method blocks if necessary until it can returnwithout making the counter negative. If not given, value defaults to 1."""def __init__(self, value=1):Semaphore.__init__(self, value)self._initial_value = valuedef release(self):"""Release a semaphore, incrementing the internal counter by one.When the counter is zero on entry and another thread is waiting for itto become larger than zero again, wake up that thread.If the number of releases exceeds the number of acquires,raise a ValueError."""with self._cond:if self._value >= self._initial_value:raise ValueError("Semaphore released too many times")self._value += 1self._cond.notify()class Event:"""Class implementing event objects.Events manage a flag that can be set to true with the set() method and resetto false with the clear() method. The wait() method blocks until the flag istrue. The flag is initially false."""# After Tim Peters' event class (without is_posted())def __init__(self):self._cond = Condition(Lock())self._flag = Falsedef _reset_internal_locks(self):# private! called by Thread._reset_internal_locks by _after_fork()self._cond.__init__(Lock())def is_set(self):"""Return true if and only if the internal flag is true."""return self._flagisSet = is_setdef set(self):"""Set the internal flag to true.All threads waiting for it to become true are awakened. Threadsthat call wait() once the flag is true will not block at all."""with self._cond:self._flag = Trueself._cond.notify_all()def clear(self):"""Reset the internal flag to false.Subsequently, threads calling wait() will block until set() is called toset the internal flag to true again."""with self._cond:self._flag = Falsedef wait(self, timeout=None):"""Block until the internal flag is true.If the internal flag is true on entry, return immediately. Otherwise,block until another thread calls set() to set the flag to true, or untilthe optional timeout occurs.When the timeout argument is present and not None, it should be afloating point number specifying a timeout for the operation in seconds(or fractions thereof).This method returns the internal flag on exit, so it will always returnTrue except if a timeout is given and the operation times out."""with self._cond:signaled = self._flagif not signaled:signaled = self._cond.wait(timeout)return signaled# A barrier class. Inspired in part by the pthread_barrier_* api and# the CyclicBarrier class from Java. See# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/# CyclicBarrier.html# for information.# We maintain two main states, 'filling' and 'draining' enabling the barrier# to be cyclic. Threads are not allowed into it until it has fully drained# since the previous cycle. In addition, a 'resetting' state exists which is# similar to 'draining' except that threads leave with a BrokenBarrierError,# and a 'broken' state in which all threads get the exception.class Barrier:"""Implements a Barrier.Useful for synchronizing a fixed number of threads at known synchronizationpoints. Threads block on 'wait()' and are simultaneously awoken once theyhave all made that call."""def __init__(self, parties, action=None, timeout=None):"""Create a barrier, initialised to 'parties' threads.'action' is a callable which, when supplied, will be called by one ofthe threads after they have all entered the barrier and just prior toreleasing them all. If a 'timeout' is provided, it is used as thedefault for all subsequent 'wait()' calls."""self._cond = Condition(Lock())self._action = actionself._timeout = timeoutself._parties = partiesself._state = 0 #0 filling, 1, draining, -1 resetting, -2 brokenself._count = 0def wait(self, timeout=None):"""Wait for the barrier.When the specified number of threads have started waiting, they are allsimultaneously awoken. If an 'action' was provided for the barrier, oneof the threads will have executed that callback prior to returning.Returns an individual index number from 0 to 'parties-1'."""if timeout is None:timeout = self._timeoutwith self._cond:self._enter() # Block while the barrier drains.index = self._countself._count += 1try:if index + 1 == self._parties:# We release the barrierself._release()else:# We wait until someone releases usself._wait(timeout)return indexfinally:self._count -= 1# Wake up any threads waiting for barrier to drain.self._exit()# Block until the barrier is ready for us, or raise an exception# if it is broken.def _enter(self):while self._state in (-1, 1):# It is draining or resetting, wait until doneself._cond.wait()#see if the barrier is in a broken stateif self._state < 0:raise BrokenBarrierErrorassert self._state == 0# Optionally run the 'action' and release the threads waiting# in the barrier.def _release(self):try:if self._action:self._action()# enter draining stateself._state = 1self._cond.notify_all()except:#an exception during the _action handler. Break and reraiseself._break()raise# Wait in the barrier until we are released. Raise an exception# if the barrier is reset or broken.def _wait(self, timeout):if not self._cond.wait_for(lambda : self._state != 0, timeout):#timed out. Break the barrierself._break()raise BrokenBarrierErrorif self._state < 0:raise BrokenBarrierErrorassert self._state == 1# If we are the last thread to exit the barrier, signal any threads# waiting for the barrier to drain.def _exit(self):if self._count == 0:if self._state in (-1, 1):#resetting or drainingself._state = 0self._cond.notify_all()def reset(self):"""Reset the barrier to the initial state.Any threads currently waiting will get the BrokenBarrier exceptionraised."""with self._cond:if self._count > 0:if self._state == 0:#reset the barrier, waking up threadsself._state = -1elif self._state == -2:#was broken, set it to reset state#which clears when the last thread exitsself._state = -1else:self._state = 0self._cond.notify_all()def abort(self):"""Place the barrier into a 'broken' state.Useful in case of error. Any currently waiting threads and threadsattempting to 'wait()' will have BrokenBarrierError raised."""with self._cond:self._break()def _break(self):# An internal error was detected. The barrier is set to# a broken state all parties awakened.self._state = -2self._cond.notify_all()@propertydef parties(self):"""Return the number of threads required to trip the barrier."""return self._parties@propertydef n_waiting(self):"""Return the number of threads currently waiting at the barrier."""# We don't need synchronization here since this is an ephemeral result# anyway. It returns the correct value in the steady state.if self._state == 0:return self._countreturn 0@propertydef broken(self):"""Return True if the barrier is in a broken state."""return self._state == -2# exception raised by the Barrier classclass BrokenBarrierError(RuntimeError):pass# Helper to generate new thread names_counter = _count().__next___counter() # Consume 0 so first non-main thread has id 1.def _newname(template="Thread-%d"):return template % _counter()# Active thread administration_active_limbo_lock = _allocate_lock()_active = {} # maps thread id to Thread object_limbo = {}_dangling = WeakSet()# Set of Thread._tstate_lock locks of non-daemon threads used by _shutdown()# to wait until all Python thread states get deleted:# see Thread._set_tstate_lock()._shutdown_locks_lock = _allocate_lock()_shutdown_locks = set()# Main class for threadsclass Thread:"""A class that represents a thread of control.This class can be safely subclassed in a limited fashion. There are two waysto specify the activity: by passing a callable object to the constructor, orby overriding the run() method in a subclass."""_initialized = Falsedef __init__(self, group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None):"""This constructor should always be called with keyword arguments. Arguments are:*group* should be None; reserved for future extension when a ThreadGroupclass is implemented.*target* is the callable object to be invoked by the run()method. Defaults to None, meaning nothing is called.*name* is the thread name. By default, a unique name is constructed ofthe form "Thread-N" where N is a small decimal number.*args* is the argument tuple for the target invocation. Defaults to ().*kwargs* is a dictionary of keyword arguments for the targetinvocation. Defaults to {}.If a subclass overrides the constructor, it must make sure to invokethe base class constructor (Thread.__init__()) before doing anythingelse to the thread."""assert group is None, "group argument must be None for now"if kwargs is None:kwargs = {}self._target = targetself._name = str(name or _newname())self._args = argsself._kwargs = kwargsif daemon is not None:self._daemonic = daemonelse:self._daemonic = current_thread().daemonself._ident = Noneif _HAVE_THREAD_NATIVE_ID:self._native_id = Noneself._tstate_lock = Noneself._started = Event()self._is_stopped = Falseself._initialized = True# Copy of sys.stderr used by self._invoke_excepthook()self._stderr = _sys.stderrself._invoke_excepthook = _make_invoke_excepthook()# For debugging and _after_fork()_dangling.add(self)def _reset_internal_locks(self, is_alive):# private! Called by _after_fork() to reset our internal locks as# they may be in an invalid state leading to a deadlock or crash.self._started._reset_internal_locks()if is_alive:self._set_tstate_lock()else:# The thread isn't alive after fork: it doesn't have a tstate# anymore.self._is_stopped = Trueself._tstate_lock = Nonedef __repr__(self):assert self._initialized, "Thread.__init__() was not called"status = "initial"if self._started.is_set():status = "started"self.is_alive() # easy way to get ._is_stopped set when appropriateif self._is_stopped:status = "stopped"if self._daemonic:status += " daemon"if self._ident is not None:status += " %s" % self._identreturn "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)def start(self):"""Start the thread's activity.It must be called at most once per thread object. It arranges for theobject's run() method to be invoked in a separate thread of control.This method will raise a RuntimeError if called more than once on thesame thread object."""if not self._initialized:raise RuntimeError("thread.__init__() not called")if self._started.is_set():raise RuntimeError("threads can only be started once")with _active_limbo_lock:_limbo[self] = selftry:_start_new_thread(self._bootstrap, ())except Exception:with _active_limbo_lock:del _limbo[self]raiseself._started.wait()def run(self):"""Method representing the thread's activity.You may override this method in a subclass. The standard run() methodinvokes the callable object passed to the object's constructor as thetarget argument, if any, with sequential and keyword arguments takenfrom the args and kwargs arguments, respectively."""try:if self._target:self._target(*self._args, **self._kwargs)finally:# Avoid a refcycle if the thread is running a function with# an argument that has a member that points to the thread.del self._target, self._args, self._kwargsdef _bootstrap(self):# Wrapper around the real bootstrap code that ignores# exceptions during interpreter cleanup. Those typically# happen when a daemon thread wakes up at an unfortunate# moment, finds the world around it destroyed, and raises some# random exception *** while trying to report the exception in# _bootstrap_inner() below ***. Those random exceptions# don't help anybody, and they confuse users, so we suppress# them. We suppress them only when it appears that the world# indeed has already been destroyed, so that exceptions in# _bootstrap_inner() during normal business hours are properly# reported. Also, we only suppress them for daemonic threads;# if a non-daemonic encounters this, something else is wrong.try:self._bootstrap_inner()except:if self._daemonic and _sys is None:returnraisedef _set_ident(self):self._ident = get_ident()if _HAVE_THREAD_NATIVE_ID:def _set_native_id(self):self._native_id = get_native_id()def _set_tstate_lock(self):"""Set a lock object which will be released by the interpreter whenthe underlying thread state (see pystate.h) gets deleted."""self._tstate_lock = _set_sentinel()self._tstate_lock.acquire()if not self.daemon:with _shutdown_locks_lock:_shutdown_locks.add(self._tstate_lock)def _bootstrap_inner(self):try:self._set_ident()self._set_tstate_lock()if _HAVE_THREAD_NATIVE_ID:self._set_native_id()self._started.set()with _active_limbo_lock:_active[self._ident] = selfdel _limbo[self]if _trace_hook:_sys.settrace(_trace_hook)if _profile_hook:_sys.setprofile(_profile_hook)try:self.run()except:self._invoke_excepthook(self)finally:with _active_limbo_lock:try:# We don't call self._delete() because it also# grabs _active_limbo_lock.del _active[get_ident()]except:passdef _stop(self):# After calling ._stop(), .is_alive() returns False and .join() returns# immediately. ._tstate_lock must be released before calling ._stop().## Normal case: C code at the end of the thread's life# (release_sentinel in _threadmodule.c) releases ._tstate_lock, and# that's detected by our ._wait_for_tstate_lock(), called by .join()# and .is_alive(). Any number of threads _may_ call ._stop()# simultaneously (for example, if multiple threads are blocked in# .join() calls), and they're not serialized. That's harmless -# they'll just make redundant rebindings of ._is_stopped and# ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the# "assert self._is_stopped" in ._wait_for_tstate_lock() always works# (the assert is executed only if ._tstate_lock is None).## Special case: _main_thread releases ._tstate_lock via this# module's _shutdown() function.lock = self._tstate_lockif lock is not None:assert not lock.locked()self._is_stopped = Trueself._tstate_lock = Noneif not self.daemon:with _shutdown_locks_lock:_shutdown_locks.discard(lock)def _delete(self):"Remove current thread from the dict of currently running threads."with _active_limbo_lock:del _active[get_ident()]# There must not be any python code between the previous line# and after the lock is released. Otherwise a tracing function# could try to acquire the lock again in the same thread, (in# current_thread()), and would block.def join(self, timeout=None):"""Wait until the thread terminates.This blocks the calling thread until the thread whose join() method iscalled terminates -- either normally or through an unhandled exceptionor until the optional timeout occurs.When the timeout argument is present and not None, it should be afloating point number specifying a timeout for the operation in seconds(or fractions thereof). As join() always returns None, you must callis_alive() after join() to decide whether a timeout happened -- if thethread is still alive, the join() call timed out.When the timeout argument is not present or None, the operation willblock until the thread terminates.A thread can be join()ed many times.join() raises a RuntimeError if an attempt is made to join the currentthread as that would cause a deadlock. It is also an error to join() athread before it has been started and attempts to do so raises the sameexception."""if not self._initialized:raise RuntimeError("Thread.__init__() not called")if not self._started.is_set():raise RuntimeError("cannot join thread before it is started")if self is current_thread():raise RuntimeError("cannot join current thread")if timeout is None:self._wait_for_tstate_lock()else:# the behavior of a negative timeout isn't documented, but# historically .join(timeout=x) for x<0 has acted as if timeout=0self._wait_for_tstate_lock(timeout=max(timeout, 0))def _wait_for_tstate_lock(self, block=True, timeout=-1):# Issue #18808: wait for the thread state to be gone.# At the end of the thread's life, after all knowledge of the thread# is removed from C data structures, C code releases our _tstate_lock.# This method passes its arguments to _tstate_lock.acquire().# If the lock is acquired, the C code is done, and self._stop() is# called. That sets ._is_stopped to True, and ._tstate_lock to None.lock = self._tstate_lockif lock is None: # already determined that the C code is doneassert self._is_stoppedelif lock.acquire(block, timeout):lock.release()self._stop()@propertydef name(self):"""A string used for identification purposes only.It has no semantics. Multiple threads may be given the same name. Theinitial name is set by the constructor."""assert self._initialized, "Thread.__init__() not called"return self._name@name.setterdef name(self, name):assert self._initialized, "Thread.__init__() not called"self._name = str(name)@propertydef ident(self):"""Thread identifier of this thread or None if it has not been started.This is a nonzero integer. See the get_ident() function. Threadidentifiers may be recycled when a thread exits and another thread iscreated. The identifier is available even after the thread has exited."""assert self._initialized, "Thread.__init__() not called"return self._identif _HAVE_THREAD_NATIVE_ID:@propertydef native_id(self):"""Native integral thread ID of this thread, or None if it has not been started.This is a non-negative integer. See the get_native_id() function.This represents the Thread ID as reported by the kernel."""assert self._initialized, "Thread.__init__() not called"return self._native_iddef is_alive(self):"""Return whether the thread is alive.This method returns True just before the run() method starts until justafter the run() method terminates. The module function enumerate()returns a list of all alive threads."""assert self._initialized, "Thread.__init__() not called"if self._is_stopped or not self._started.is_set():return Falseself._wait_for_tstate_lock(False)return not self._is_stoppeddef isAlive(self):"""Return whether the thread is alive.This method is deprecated, use is_alive() instead."""import warningswarnings.warn('isAlive() is deprecated, use is_alive() instead',DeprecationWarning, stacklevel=2)return self.is_alive()@propertydef daemon(self):"""A boolean value indicating whether this thread is a daemon thread.This must be set before start() is called, otherwise RuntimeError israised. Its initial value is inherited from the creating thread; themain thread is not a daemon thread and therefore all threads created inthe main thread default to daemon = False.The entire Python program exits when only daemon threads are left."""assert self._initialized, "Thread.__init__() not called"return self._daemonic@daemon.setterdef daemon(self, daemonic):if not self._initialized:raise RuntimeError("Thread.__init__() not called")if self._started.is_set():raise RuntimeError("cannot set daemon status of active thread")self._daemonic = daemonicdef isDaemon(self):return self.daemondef setDaemon(self, daemonic):self.daemon = daemonicdef getName(self):return self.namedef setName(self, name):self.name = nametry:from _thread import (_excepthook as excepthook,_ExceptHookArgs as ExceptHookArgs)except ImportError:# Simple Python implementation if _thread._excepthook() is not availablefrom traceback import print_exception as _print_exceptionfrom collections import namedtuple_ExceptHookArgs = namedtuple('ExceptHookArgs','exc_type exc_value exc_traceback thread')def ExceptHookArgs(args):return _ExceptHookArgs(*args)def excepthook(args, /):"""Handle uncaught Thread.run() exception."""if args.exc_type == SystemExit:# silently ignore SystemExitreturnif _sys is not None and _sys.stderr is not None:stderr = _sys.stderrelif args.thread is not None:stderr = args.thread._stderrif stderr is None:# do nothing if sys.stderr is None and sys.stderr was None# when the thread was createdreturnelse:# do nothing if sys.stderr is None and args.thread is Nonereturnif args.thread is not None:name = args.thread.nameelse:name = get_ident()print(f"Exception in thread {name}:",file=stderr, flush=True)_print_exception(args.exc_type, args.exc_value, args.exc_traceback,file=stderr)stderr.flush()def _make_invoke_excepthook():# Create a local namespace to ensure that variables remain alive# when _invoke_excepthook() is called, even if it is called late during# Python shutdown. It is mostly needed for daemon threads.old_excepthook = excepthookold_sys_excepthook = _sys.excepthookif old_excepthook is None:raise RuntimeError("threading.excepthook is None")if old_sys_excepthook is None:raise RuntimeError("sys.excepthook is None")sys_exc_info = _sys.exc_infolocal_print = printlocal_sys = _sysdef invoke_excepthook(thread):global excepthooktry:hook = excepthookif hook is None:hook = old_excepthookargs = ExceptHookArgs([*sys_exc_info(), thread])hook(args)except Exception as exc:exc.__suppress_context__ = Truedel excif local_sys is not None and local_sys.stderr is not None:stderr = local_sys.stderrelse:stderr = thread._stderrlocal_print("Exception in threading.excepthook:",file=stderr, flush=True)if local_sys is not None and local_sys.excepthook is not None:sys_excepthook = local_sys.excepthookelse:sys_excepthook = old_sys_excepthooksys_excepthook(*sys_exc_info())finally:# Break reference cycle (exception stored in a variable)args = Nonereturn invoke_excepthook# The timer class was contributed by Itamar Shtull-Trauringclass Timer(Thread):"""Call a function after a specified number of seconds:t = Timer(30.0, f, args=None, kwargs=None)t.start()t.cancel() # stop the timer's action if it's still waiting"""def __init__(self, interval, function, args=None, kwargs=None):Thread.__init__(self)self.interval = intervalself.function = functionself.args = args if args is not None else []self.kwargs = kwargs if kwargs is not None else {}self.finished = Event()def cancel(self):"""Stop the timer if it hasn't finished yet."""self.finished.set()def run(self):self.finished.wait(self.interval)if not self.finished.is_set():self.function(*self.args, **self.kwargs)self.finished.set()# Special thread class to represent the main threadclass _MainThread(Thread):def __init__(self):Thread.__init__(self, name="MainThread", daemon=False)self._set_tstate_lock()self._started.set()self._set_ident()if _HAVE_THREAD_NATIVE_ID:self._set_native_id()with _active_limbo_lock:_active[self._ident] = self# Dummy thread class to represent threads not started here.# These aren't garbage collected when they die, nor can they be waited for.# If they invoke anything in threading.py that calls current_thread(), they# leave an entry in the _active dict forever after.# Their purpose is to return *something* from current_thread().# They are marked as daemon threads so we won't wait for them# when we exit (conform previous semantics).class _DummyThread(Thread):def __init__(self):Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)self._started.set()self._set_ident()if _HAVE_THREAD_NATIVE_ID:self._set_native_id()with _active_limbo_lock:_active[self._ident] = selfdef _stop(self):passdef is_alive(self):assert not self._is_stopped and self._started.is_set()return Truedef join(self, timeout=None):assert False, "cannot join a dummy thread"# Global API functionsdef current_thread():"""Return the current Thread object, corresponding to the caller's thread of control.If the caller's thread of control was not created through the threadingmodule, a dummy thread object with limited functionality is returned."""try:return _active[get_ident()]except KeyError:return _DummyThread()currentThread = current_threaddef active_count():"""Return the number of Thread objects currently alive.The returned count is equal to the length of the list returned byenumerate()."""with _active_limbo_lock:return len(_active) + len(_limbo)activeCount = active_countdef _enumerate():# Same as enumerate(), but without the lock. Internal use only.return list(_active.values()) + list(_limbo.values())def enumerate():"""Return a list of all Thread objects currently alive.The list includes daemonic threads, dummy thread objects created bycurrent_thread(), and the main thread. It excludes terminated threads andthreads that have not yet been started."""with _active_limbo_lock:return list(_active.values()) + list(_limbo.values())from _thread import stack_size# Create the main thread object,# and make it available for the interpreter# (Py_Main) as threading._shutdown._main_thread = _MainThread()def _shutdown():"""Wait until the Python thread state of all non-daemon threads get deleted."""# Obscure: other threads may be waiting to join _main_thread. That's# dubious, but some code does it. We can't wait for C code to release# the main thread's tstate_lock - that won't happen until the interpreter# is nearly dead. So we release it here. Note that just calling _stop()# isn't enough: other threads may already be waiting on _tstate_lock.if _main_thread._is_stopped:# _shutdown() was already calledreturn# Main threadtlock = _main_thread._tstate_lock# The main thread isn't finished yet, so its thread state lock can't have# been released.assert tlock is not Noneassert tlock.locked()tlock.release()_main_thread._stop()# Join all non-deamon threadswhile True:with _shutdown_locks_lock:locks = list(_shutdown_locks)_shutdown_locks.clear()if not locks:breakfor lock in locks:# mimick Thread.join()lock.acquire()lock.release()# new threads can be spawned while we were waiting for the other# threads to completedef main_thread():"""Return the main thread object.In normal conditions, the main thread is the thread from which thePython interpreter was started."""return _main_thread# get thread-local implementation, either from the thread# module, or from the python fallbacktry:from _thread import _local as localexcept ImportError:from _threading_local import localdef _after_fork():"""Cleanup threading module state that should not exist after a fork."""# Reset _active_limbo_lock, in case we forked while the lock was held# by another (non-forked) thread. http://bugs.python.org/issue874900global _active_limbo_lock, _main_threadglobal _shutdown_locks_lock, _shutdown_locks_active_limbo_lock = _allocate_lock()# fork() only copied the current thread; clear references to others.new_active = {}try:current = _active[get_ident()]except KeyError:# fork() was called in a thread which was not spawned# by threading.Thread. For example, a thread spawned# by thread.start_new_thread().current = _MainThread()_main_thread = current# reset _shutdown() locks: threads re-register their _tstate_lock below_shutdown_locks_lock = _allocate_lock()_shutdown_locks = set()with _active_limbo_lock:# Dangling thread instances must still have their locks reset,# because someone may join() them.threads = set(_enumerate())threads.update(_dangling)for thread in threads:# Any lock/condition variable may be currently locked or in an# invalid state, so we reinitialize them.if thread is current:# There is only one active thread. We reset the ident to# its new value since it can have changed.thread._reset_internal_locks(True)ident = get_ident()thread._ident = identnew_active[ident] = threadelse:# All the others are already stopped.thread._reset_internal_locks(False)thread._stop()_limbo.clear()_active.clear()_active.update(new_active)assert len(_active) == 1if hasattr(_os, "register_at_fork"):_os.register_at_fork(after_in_child=_after_fork)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。