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.
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.
Syntax:Threadname.setDaemon(True)
Source code:
import threading
import time
def Thread1():
print(' Starting ')
print(threading.currentThread().getName())
print('Exiting',threading.currentThread().getName())
def Thread2():
print(threading.currentThread().getName())
print('Starting ')
time.sleep(5)
print('Exiting',threading.currentThread().getName())
if __name__ == '__main__':
Thread1 = threading.Thread(name='non-daemon', target=Thread1)
Thread2 = threading.Thread(name='daemon', target=Thread2)
Thread2.setDaemon(True)
Thread2.start()
Thread1.start()
output:
Name | Views | Likes |
---|---|---|
Python threading Timer | 890 | 0 |
Python threading getName | 423 | 0 |
Program to count "Number of Vowels" in the string | 350 | 0 |
Python threading isAlive | 1588 | 0 |
Python threading introduction | 811 | 0 |
Python threading setName | 1216 | 0 |
Python threading isDaemon | 742 | 0 |
Python threading get_ident | 470 | 0 |
Python threading currentThread | 459 | 0 |
Python threading active_count | 441 | 0 |
Python threading enumerate | 508 | 0 |
Python threading setDaemon | 1062 | 0 |
Python threading main_thread | 432 | 0 |
Python threading cancel | 504 | 0 |
Comments