Daemon Threads Explanation

In the Python documentation it says:

A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.

Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as daemonic ?


To clarify for me:

so the only time you wouldn't set threads as daemonic is if you wanted them to continue running after the main thread exits?


Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you'd 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.


Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  • Connect to the mail server and ask how many unread messages you have.
  • Signal the GUI with the updated count.
  • Sleep for a little while.
  • When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.


    A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.

    A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.

    链接地址: http://www.djcxy.com/p/54784.html

    上一篇: 迭代器,迭代器和迭代究竟是什么?

    下一篇: 守护线程说明