Sunday 20 December 2015

Python: Daemon threads

Daemon threads are low priority threads, which are mainly used for background processing.

How to make a thread as daemon thread
‘setDaemon(True)’ is used to make a thread as daemon thread (or) by setting the property daemon to True. The daemon value must be set before calling the start method of the thread.

How to check whether thread is daemon or not
‘isDaemon()’ method returns True if the thread is daemon, else false.

daemon property
A boolean value indicating whether this thread is a daemon thread (True) or not (False).

Since main thread is not a daemon thread, all the threads that are created under main thread are not daemon threads. If you create a thread under daemon thread, that thread is also a daemon thread.


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  print(threading.current_thread().getName()," is Daemon : ", threading.current_thread().isDaemon())
  
thread1 = MyThread(name="Thread_1")
thread2 = MyThread(name="Thread_2")
thread3 = MyThread(name="Thread_3")

thread2.setDaemon(True)
thread3.daemon=True

thread1.start()
thread2.start()
thread3.start()

$ python3 MyThread.py 
Thread_1  is Daemon :  False
Thread_2  is Daemon :  True
Thread_3  is Daemon :  True

Python program closes its execution, when no other non-daemon thread is alive.


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  time.sleep(2)
  print(threading.current_thread().getName()," Finished")
  
thread1 = MyThread(name="Thread_1")

thread1.start()

print("Main thread Finished Execution")

$ python3 MyThread.py 
Main thread Finished Execution
Thread_1  Finished


Since thread1 is not a daemon thread, main thread waits until thread1 finishes its execution. Now lets make thread1 as daemon thread and re run the application.

MyThread.py

import threading
import time

class MyThread(threading.Thread):
 def run(self):
  time.sleep(2)
  print(threading.current_thread().getName()," Finished")
  
thread1 = MyThread(name="Thread_1")

thread1.daemon=True
thread1.start()

print("Main thread Finished Execution")


$ python3 MyThread.py 
Main thread Finished Execution
$


Observe the output, Main thread finished execution and not wait for thread1(Since thread1 is a daemon thread).





Previous                                                 Next                                                 Home

No comments:

Post a Comment