【问题标题】:how to make a thread in a thread subclass daemon?如何在线程子类守护进程中创建线程?
【发布时间】:2022-01-12 02:19:20
【问题描述】:
如何在下面的类守护进程中创建踏板,以便在程序结束后停止?
import threading
import time
class A_Class(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running")
time.sleep(1)
a_obj = A_Class()
a_obj.start()
time.sleep(5)
print('The time is up, the thread should end')
【问题讨论】:
标签:
python
multithreading
daemon
【解决方案1】:
您应该将daemon=True 添加到您的Thread.__init__():
import threading
import time
class A_Class(threading.Thread):
def __init__(self):
threading.Thread.__init__(self, daemon=True)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running")
time.sleep(1)
a_obj = A_Class()
a_obj.start()
time.sleep(5)
print('The time is up, the thread should end')
【解决方案2】:
另一种方法 - 在调用 super().__init__() 后将其设置为守护进程。
class A_Class(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
def __del__(self):
print('deleted')
def run(self):
while True:
print("running", self.isDaemon())
time.sleep(1)
或者使用关键字参数:
class A_Class(threading.Thread):
def __init__(self,*args,**kwargs):
super().__init__(**kwargs)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running", self.isDaemon())
time.sleep(1)
a_obj = A_Class(daemon=True)