在python中实现强制关闭线程的示例
如下所示:
importthreading importtime importinspect importctypes def_async_raise(tid,exctype): """raisestheexception,performscleanupifneeded""" tid=ctypes.c_long(tid) ifnotinspect.isclass(exctype): exctype=type(exctype) res=ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,ctypes.py_object(exctype)) ifres==0: raiseValueError("invalidthreadid") elifres!=1: #"""ifitreturnsanumbergreaterthanone,you'reintrouble, #andyoushouldcallitagainwithexc=NULLtoreverttheeffect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,None) raiseSystemError("PyThreadState_SetAsyncExcfailed") defstop_thread(thread): _async_raise(thread.ident,SystemExit) classTestThread(threading.Thread): defrun(self): print "begin" whileTrue: time.sleep(0.1) print('end') if__name__=="__main__": t=TestThread() t.start() time.sleep(1) stop_thread(t) print('stoped')
以上这篇在python中实现强制关闭线程的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。