The flow of daemon thread over 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 modules from threading import * import time # creating a function def thread_1(): for i in range ( 5 ): print ( 'this is thread T' ) time.sleep( 3 ) # creating a thread T = Thread(target = thread_1) # change T to daemon T.setDaemon( True ) # starting of Thread T T.start() time.sleep( 5 ) print ( 'this is Main Thread' ) |
Output:
this is thread T this is thread T this is Main Thread
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.