Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading