Change Non-Daemon To Daemon
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 module from threading import * def fun(): print ( "Geeks For Geeks" ) T = Thread(target = fun) print ( "GFG" ) print (T.isDaemon()) # set thread as Daemon T.setDaemon( True ) # check status print (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.
Python Daemon Threads
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.