Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a thread in a thread subclass daemon?

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')
like image 818
gero Avatar asked Nov 04 '25 11:11

gero


2 Answers

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')
like image 159
Oleksii Tambovtsev Avatar answered Nov 07 '25 00:11

Oleksii Tambovtsev


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)
like image 24
wwii Avatar answered Nov 07 '25 01:11

wwii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!