【python笔记】关闭守护线程的2种方法
关闭守护线程
1、守护线程,和主线程并行,互不影响;
2、当主线程关闭后守护线程自动关闭。
创建和启动守护线程
下面展示创建和启动
。
import threading
...
# 创建线程
threadSent = threading.Thread(target=self.SentUdpMessage)
# 定义为守护线程
threadSent.setDaemon = True
# 启动守护线程
threadSent.start()
...
提前关闭守护线程
方法1:创建stop方法
import threading
import inspect
import ctypes
...
# 创建stop方法
def _async_raise(tid, exctype):
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:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
print("====线程已关闭")
...
# 创建线程
threadSent = threading.Thread(target=SentUdpMessage)
# 定义为守护线程
threadSent.setDaemon = True
# 启动守护线程
threadSent.start()
...
# 调用stop方法
stop_thread(threadSent)
...
方法2:定义全局变量的关闭线程开关(适用于函数内while循环类型的线程)
import threading
class A:
def setup(self):
self.stop_threads = False
def teardown(self):
pass
def SentUdpMessage(self):
while True:
print("启动SentUdpMessage")
if self.stop_threads == True
print("====线程已关闭")
break
def run(self):
...
# 创建线程
threadSent = threading.Thread(target=SentUdpMessage)
# 定义为守护线程
threadSent.setDaemon = True
# 启动守护线程
threadSent.start()
...
# 触发关闭线程动作
self.stop_threads = True
...
以上over 2023/5/10