需要对threading.Thread进行重写
在代码中添加
# 重写threading.Thread方法,添加了kill(),结束线程
class multi_thread(threading.Thread):
def __init__(self, *params, **known):
super(multi_thread, self).__init__(*params, **known)
parent_thread = threading.current_thread()
self.is_killed = False
self.child_threads = []
if hasattr(parent_thread, 'child_threads'):
parent_thread.child_threads.append(self)
def _raise_exc(self, exc_obj):
if not self.is_alive():
return
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(self.ident), ctypes.py_object(exc_obj))
if res == 0:
raise RuntimeError("Not existent thread id.")
elif res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, None)
raise SystemError("PyThreadState_SetAsyncExc failed.")
def kill(self):
if hasattr(self, 'child_threads'):
for child_thread in self.child_threads:
if child_thread.is_alive():
child_thread.kill()
self._raise_exc(SystemExit)
self.is_killed = True
使用时使用:
thread = multi_thread(target=self.download_img)
thread.start()
代替
threading.Thread(target=self.download_img).start()
使用:
线程名.kill()即可
有用的话,点个赞再走吧QAQ