python终止线程的方法
小编给大家分享一下python终止线程的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
在python中启动和关闭线程:
一、启动线程
首先导入threading
importthreading
然后定义一个方法
defserial_read():......
然后定义线程,target指向要执行的方法
myThread=threading.Thread(target=serial_read)
启动它
myThread.start()
二、停止线程
importinspectimportctypesdef_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)
停止线程
stop_thread(myThread)
stop方法可以强行终止正在运行或挂起的线程。
看完了这篇文章,相信你对python终止线程的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。