"""Drop-in replacement for the thread module.Meant to be used as a brain-dead substitute so that threaded code doesnot need to be rewritten for when the thread module is not present.Suggested usage is::try:import _threadexcept ImportError:import _dummy_thread as _thread"""# Exports only things specified by thread documentation;# skipping obsolete synonyms allocate(), start_new(), exit_thread().__all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock','interrupt_main', 'LockType', 'RLock']# A dummy valueTIMEOUT_MAX = 2**31# NOTE: this module can be imported early in the extension building process,# and so top level imports of other modules should be avoided. Instead, all# imports are done when needed on a function-by-function basis. Since threads# are disabled, the import lock should not be an issue anyway (??).error = RuntimeErrordef start_new_thread(function, args, kwargs={}):"""Dummy implementation of _thread.start_new_thread().Compatibility is maintained by making sure that ``args`` is atuple and ``kwargs`` is a dictionary. If an exception is raisedand it is SystemExit (which can be done by _thread.exit()) it iscaught and nothing is done; all other exceptions are printed outby using traceback.print_exc().If the executed function calls interrupt_main the KeyboardInterrupt will beraised when the function returns."""if type(args) != type(tuple()):raise TypeError("2nd arg must be a tuple")if type(kwargs) != type(dict()):raise TypeError("3rd arg must be a dict")global _main_main = Falsetry:function(*args, **kwargs)except SystemExit:passexcept:import tracebacktraceback.print_exc()_main = Trueglobal _interruptif _interrupt:_interrupt = Falseraise KeyboardInterruptdef exit():"""Dummy implementation of _thread.exit()."""raise SystemExitdef get_ident():"""Dummy implementation of _thread.get_ident().Since this module should only be used when _threadmodule is notavailable, it is safe to assume that the current process is theonly thread. Thus a constant can be safely returned."""return 1def allocate_lock():"""Dummy implementation of _thread.allocate_lock()."""return LockType()def stack_size(size=None):"""Dummy implementation of _thread.stack_size()."""if size is not None:raise error("setting thread stack size not supported")return 0def _set_sentinel():"""Dummy implementation of _thread._set_sentinel()."""return LockType()class LockType(object):"""Class implementing dummy implementation of _thread.LockType.Compatibility is maintained by maintaining self.locked_statuswhich is a boolean that stores the state of the lock. Pickling ofthe lock, though, should not be done since if the _thread module isthen used with an unpickled ``lock()`` from here problems couldoccur from this class not having atomic methods."""def __init__(self):self.locked_status = Falsedef acquire(self, waitflag=None, timeout=-1):"""Dummy implementation of acquire().For blocking calls, self.locked_status is automatically set toTrue and returned appropriately based on value of``waitflag``. If it is non-blocking, then the value isactually checked and not set if it is already acquired. Thisis all done so that threading.Condition's assert statementsaren't triggered and throw a little fit."""if waitflag is None or waitflag:self.locked_status = Truereturn Trueelse:if not self.locked_status:self.locked_status = Truereturn Trueelse:if timeout > 0:import timetime.sleep(timeout)return False__enter__ = acquiredef __exit__(self, typ, val, tb):self.release()def release(self):"""Release the dummy lock."""# XXX Perhaps shouldn't actually bother to test? Could lead# to problems for complex, threaded code.if not self.locked_status:raise errorself.locked_status = Falsereturn Truedef locked(self):return self.locked_statusdef __repr__(self):return "<%s %s.%s object at %s>" % ("locked" if self.locked_status else "unlocked",self.__class__.__module__,self.__class__.__qualname__,hex(id(self)))class RLock(LockType):"""Dummy implementation of threading._RLock.Re-entrant lock can be aquired multiple times and needs to be releasedjust as many times. This dummy implemention does not check wheter thecurrent thread actually owns the lock, but does accounting on the callcounts."""def __init__(self):super().__init__()self._levels = 0def acquire(self, waitflag=None, timeout=-1):"""Aquire the lock, can be called multiple times in succession."""locked = super().acquire(waitflag, timeout)if locked:self._levels += 1return lockeddef release(self):"""Release needs to be called once for every call to acquire()."""if self._levels == 0:raise errorif self._levels == 1:super().release()self._levels -= 1# Used to signal that interrupt_main was called in a "thread"_interrupt = False# True when not executing in a "thread"_main = Truedef interrupt_main():"""Set _interrupt flag to True to have start_new_thread raiseKeyboardInterrupt upon exiting."""if _main:raise KeyboardInterruptelse:global _interrupt_interrupt = True
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。