Methods To Check Whether Thread Is Daemon or Non-Daemon
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 module from 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 module from 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
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.