Python Thread - daemon property

 

Daemon Threads

daemon-This property that is set on a python thread object makes a thread daemonic.A daemon thread does not block the main thread from exiting and continues to run in the background. In the below example, the print statements from the daemon thread will not printed to the console as the main thread exits. 

Example:

from threading import Thread;

import os

import time

 

# class defining Daemon Thread

class DaemonThread(Thread):

 

    # Daemon Thread constructor

    def __init__(self):

        Thread.__init__(self)

 

    # Daemon Thread run method

    def run(self):

        for i in range(1,10):

            print("I am the daemon thread. I keep on running bg...hehe")

            time.sleep(2)

 

# Main thread

aDaemonThread = DaemonThread()

aDaemonThread.daemon = False

aDaemonThread.start()

print("My Daemon will take care")


Copyright 2024 © pythontic.com