Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference it makes when I set python thread as a Daemon

What difference makes it when I set a python thread as a daemon, using thread.setDaemon(True)?

like image 392
Vijayendra Bapte Avatar asked Sep 11 '09 16:09

Vijayendra Bapte


People also ask

What does daemon do in threading Python?

daemon-This property that is set on a python thread object makes a thread daemonic. A daemon thread does not block the main thread from exiting and continues to run in the background. In the below example, the print statements from the daemon thread will not printed to the console as the main thread exits.

What is difference between daemon and non-daemon thread?

Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks.

Why do we need daemon thread?

Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits. When a new thread is created it inherits the daemon status of its parent.

What does thread daemon mean?

A Daemon thread is a background service thread which runs as a low priority thread and performs background operations like garbage collection. JVM exits if only daemon threads are remaining. The setDaemon() method of the Thread class is used to mark/set a particular thread as either a daemon thread or a user thread.


1 Answers

A daemon thread will not prevent the application from exiting. The program ends when all non-daemon threads (main thread included) are complete.

So generally, if you're doing something in the background, you might want to set the thread as daemon so you don't have to explicitly have that thread's function return before the app can exit.

For example, if you are writing a GUI application and the user closes the main window, the program should quit. But if you have non-daemon threads hanging around, it won't.

From the docs: http://docs.python.org/library/threading.html#threading.Thread.daemon

Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

like image 138
FogleBird Avatar answered Oct 27 '22 10:10

FogleBird