Home > Mobile >  how to make a thread in a thread subclass daemon?
how to make a thread in a thread subclass daemon?

Time:01-12

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')

CodePudding user response:

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')

CodePudding user response:

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)
  •  Tags:  
  • Related