Daemon Threads Explanation

2019-01-01 10:08发布

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?

7条回答
忆尘夕之涩
2楼-- · 2019-01-01 10:37

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:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. 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.

查看更多
登录 后发表回答