【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 Adef 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值