python怎么关闭线程
发布时间:2026-05-17 16:05:02

Python关闭线程的方法:
1、使用setDaemonne(True)该函数的特性关闭线程
特点如下:在主线程A中,创建了子线程B,并在主线程A中调用B.setDaemon(),这意味着将主线程A设置为保护线程。此时,如果主线程A执行结束,无论子线程B是否完成,都将与主线程A一起退出。
2、强行使用ctypes杀死线程
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)
defprint_time():
while2:
print(111111111111)
print(222222222222)
print(333333333333)
print(444444444444)
print(555555555555)
print(666666666666)
if__name__=="__main__":
t=threading.Thread(target=print_time)
t.start()
stop_thread(t)
print("stoped")
while1:
pass请关注Python视频教程栏目,了解更多Python知识。
下一篇 返回列表
