Python Daemon Threads

17 Aug, 2021
The threads which are always going to run in the background that provides supports to main or non-daemon threads, those background executing threads are considered as Daemon Threads. The Daemon Thread does not block the main thread from exiting and continues to run in the background. This article is based on threading in python, here we discuss daemon thread with examples.
There is one of the best examples of a daemon thread is Garbage Collector because we assume that the main thread is executing or running, at that time any memory problem occurs then immediately python virtual machine(PVM) is going to execute Garbage Collector. The Garbage Collector is going to execute in the background and destroy all the useless objects and then free memory by default will be provided, once there is free memory will available then the main thread is going to be executed without any problem.
This example simplifies the flow of a non-daemon thread where we have created a thread_1() name function which having some lines of instructions to execute which reveal how the non-daemon thread is executed when the main thread terminates. At the next we have created the thread T of function thread_1() which is currently considered as a non-active thread, now we start the thread T, and we also have temporarily stopped the execution of the main thread for 5secs. Of time, between this 5sec. Thread T continues its execution and when the main thread is going to be executed after 5sec. Where it stops its work but there is a thread T still is in execution because it is a non-daemon thread and executes their instruction until their completion. 
Below is the implementation:
Python3
# import modulefrom threading import *import time # creating a functiondef thread_1():                  for i in range(5):    print('this is non-daemon thread')    time.sleep(2) # creating a thread TT = Thread(target=thread_1) # starting of thread TT.start()      # main thread stop execution till 5 sec.time.sleep(5)                  print('main Thread execution')
Output: 
this is non-daemon thread
this is non-daemon thread
this is non-daemon thread
main Thread execution
this is non-daemon thread
this is non-daemon thread
This is an example to show how daemon threads behave over non-daemon threads during program execution. We already see in the above example that how the non-daemon thread completes its execution after the termination of the main thread but here is something different from that. In this example, we have created a function thread_1() and thread T as same as above example but here after the creation of thread T we use setDaemon() method to change the non-daemon nature of thread T to daemon nature, then we start the thread T and temporary stops the execution of the main thread. Here is the twist when the main thread is complete their execution and terminates then thread T also terminates because this is a daemon thread, where daemon thread terminates it’s execution when the main thread terminates, work of it is to support the main thread if there is no main thread remaining why will daemon thread running there they also terminate still execution of instructions is remaining.
Below is the implementation: 
Python3
# import modulesfrom threading import *import time # creating a functiondef thread_1():                       for i in range(5):    print('this is thread T')    time.sleep(3) # creating a threadT = Thread(target = thread_1) # change T to daemonT.setDaemon(True)                   # starting of Thread TT.start()                          time.sleep(5)print('this is Main Thread') 
Output:
this is thread T
this is thread T
this is Main Thread
There are one method and one property to check the nature of the following thread:
isDaemon( )
daemon
Example 1: Program to explain isDaemon() and daemon methods.
This is a simple example to explain how we check the nature or status of the following thread, in this example, we check the nature of the main thread by using isDaemon() and daemon method. Here we use current_thread() method which simplifies which thread is currently executing, and we use it with isDaemon() and daemon method to check the nature or status of the current thread. The output of this code is False and False because current_thread is the main thread is always a non-daemon thread.
Python3
# import modulefrom threading import * print(current_thread().isDaemon())        print(current_thread().daemon)
Output:
False
False
Example 2: 
In this example we have created a function to check whether the thread is a daemon or not, then we create a new thread thread_1 which is currently a non-daemon thread and non-active thread then we check the status or nature of the thread, the output becomes False after that we start a thread now thread becomes an active thread again we check it’s status an again output is False this all means that not the main thread is non-daemon but also other created thread is also non-daemon.
Python3
# import modulefrom threading import * def fun_daemon():  print("GFG")   thread_1 = Thread(target=fun_daemon)print(thread_1.isDaemon())thread_1.start()print(thread_1.daemon)
Output:
False
GFG
False
As we previously see that how to check whether the following thread is a daemon or non-daemon, here we learn about how the following non-daemon thread can be changed into the daemon.
 A setDaemon() is the method that is used to change the non-daemon nature of a given thread into the daemon nature. setDaemon() method takes only one parameter that is a Boolean value (True or False). 
Syntax: Thread_name.setDaemon()    
# Here Thread_name  refers to name of thread that you have used.     
Parameter: (True or False)  
if True, marks this thread as a daemon thread
if False, marks this thread as a non daemon thread.
Example:
Python3
# import modulefrom threading import * def fun():    print("Geeks For Geeks") T = Thread(target = fun) print("GFG")print(T.isDaemon()) # set thread as DaemonT.setDaemon(True)  # check statusprint(T.isDaemon())T.start()
Output:
GFG
False
True
Geeks For Geeks
Explanation:
In the above example first, we import a library threading then we define a new function fun() at the next point we create a new threading variable T.  Currently, T is a non-active thread we didn’t execute the start() method yet, here we will check the status of thread T and the output comes to be False at next we use the method setDaemon() to change the nature of thread T after using the method again we will check the status of following thread at this time output will be True. 
If we want to change the main thread which is always non-daemon in nature to daemon nature then we will get a RuntimeError because when the program is started at a time main thread is also started so the main thread is an active thread and the active thread is not set to the daemon.
Example:
Python3
# import modulefrom threading import * print(current_thread().setDaemon(True))
Output: 
RuntimeError: cannot set daemon status of active thread
pranavjandu
maneesh085
Python-multithreading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.