Python threading setDaemon

Python threading setDaemon

setDaemon( ):

Basically there are two types of thread. One is daemon thread. Another is non-daemon thread.

While a non-daemon thread blocks the main program to exit if they are not dead. A daemon thread runs without blocking the main program from exiting. And when main program exits, associated daemon threads are killed too.

In computer science, a daemon is a process that runs in the background.

 A  daemon thread will shut down immediately when the program exits. 

If a program is running Threads that are not daemons, then the program will wait for those threads to complete before it terminates.Threads that are daemons, however, are just killed wherever they are when the program is exiting.

This property that is set on a python thread object makes a thread daemonic

Without daemon threads, we have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

Using daemon threads is useful for services where there may not be an easy way to interrupt the thread or where letting the thread die in the middle of its work without losing or corrupting data. To designate a thread as a daemon, we call its setDaemon() method with a boolean argument. The default setting for a thread is non-daemon. So, passing True turns the daemon mode on.


Source code:

import threading

import time

def Thread1():


    print('   Starting ')



def Thread2():


    print('Starting ')



if __name__ == '__main__':

        Thread1 = threading.Thread(name='non-daemon', target=Thread1)


        Thread2 = threading.Thread(name='daemon', target=Thread2)