How to make the tread in the below class daemon so it stops once the program ends?
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')
You should add daemon=True to your 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')
Another way to do it - set it as Daemon after calling 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)
Or use a keyword parameter:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With