如何结束一个python的线程 方法分享
import threading
flag = 0
# 为线程定义一个函数
def print_time():
def printOne():
while 1:
print(111111111111)
print(222222222222)
print(333333333333)
print(444444444444)
print(555555555555)
print(666666666666)
th1 = threading.Thread(target=printOne)
th1.setDaemon(True)
th1.start()
while 1:
if flag:
print("正在停止这个程序!!!")
break
i=5
if i == 5:
th = threading.Thread(target=print_time)
th.start()
flag=1
th.join()
print("++++++++++++++++++++++++++++++++++++++++++++++++++")
while 1:
pass执行代码,会发现孙线程并没有结束。很简单,因为孙线程它会等主线程结束,它才结束。去掉最后两行代码,孙线程就会结束,但这也是等主线程结束的。所以方法一不满足需求。
import threading
import time
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
def print_time():
while 2:
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")
while 1:
pass这个方法是在网上找的,推荐一下,非常干净利索的干掉了子线程。