<s> """<STR_LIT>""" <EOL> import ctypes <EOL> import functools <EOL> import logging <EOL> import threading <EOL> _LOG = logging . getLogger ( __name__ ) <EOL> class ThreadTerminationError ( SystemExit ) : <EOL> """<STR_LIT>""" <EOL> def Loop ( _ = None , force = False ) : <EOL> """<STR_LIT>""" <EOL> if not force : <EOL> raise AttributeError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> def RealLoop ( fn ) : <EOL> @ functools . wraps ( fn ) <EOL> def _proc ( * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> while True : <EOL> fn ( * args , ** kwargs ) <EOL> _proc . once = fn <EOL> return _proc <EOL> return RealLoop <EOL> class ExceptionSafeThread ( threading . Thread ) : <EOL> """<STR_LIT>""" <EOL> def run ( self ) : <EOL> try : <EOL> self . _ThreadProc ( ) <EOL> except Exception as exception : <EOL> if not self . _ThreadException ( exception ) : <EOL> logging . exception ( '<STR_LIT>' , self . name ) <EOL> raise <EOL> finally : <EOL> self . _ThreadFinished ( ) <EOL> _LOG . debug ( '<STR_LIT>' , self . name ) <EOL> def _ThreadProc ( self ) : <EOL> """<STR_LIT>""" <EOL> def _ThreadFinished ( self ) : <EOL> """<STR_LIT>""" <EOL> def _ThreadException ( self , exception ) : <EOL> """<STR_LIT>""" <EOL> class KillableThread ( ExceptionSafeThread ) : <EOL> """<STR_LIT>""" <EOL> def Kill ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . is_alive ( ) : <EOL> self . AsyncRaise ( ThreadTerminationError ) <EOL> def AsyncRaise ( self , exc_type ) : <EOL> """<STR_LIT>""" <EOL> assert self . is_alive ( ) , '<STR_LIT>' <EOL> result = ctypes . pythonapi . PyThreadState_SetAsyncExc ( <EOL> ctypes . c_long ( self . ident ) , ctypes . py_object ( exc_type ) ) <EOL> if result == <NUM_LIT:0> : <EOL> raise ValueError ( '<STR_LIT>' , self . ident ) <EOL> elif result != <NUM_LIT:1> : <EOL> ctypes . pythonapi . PyThreadState_SetAsyncExc ( self . ident , None ) <EOL> raise SystemError ( '<STR_LIT>' , self . ident ) <EOL> def _ThreadException ( self , exception ) : <EOL> """<STR_LIT>""" <EOL> return isinstance ( exception , ThreadTerminationError ) <EOL> class NoneByDefaultThreadLocal ( threading . local ) : <EOL> """<STR_LIT>""" <EOL> def __getattr__ ( self , _ ) : <EOL> return None <EOL> def Synchronized ( func ) : <EOL> """<STR_LIT>""" <EOL> @ functools . wraps ( func ) <EOL> def synchronized_method ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> with self . _lock : <EOL> return func ( self , * args , ** kwargs ) <EOL> return synchronized_method </s>
