[Python]Threading.ThreadのDaemonスレッド

2241 ワード

以前はDaemonスレッドの理解にずれがあったので、特記録の説明は以下の通りである.
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. The flag can be set through the daemon property.
        "Daemon  ",Daemon      Python      Daemon          。          ,   setDaemon()      。
Note Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event. Daemonスレッドは乱暴に直接終了し、使用するリソース(オープンファイル、データベーストランザクションなど)は合理的に解放されません.したがって、スレッドが優雅に終了する必要がある場合は、Daemonスレッド以外に設定し、イベントイベントなどの合理的な信号方法を使用します.
daemon
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. 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.
isDaemon()
setDaemon()

Pythonメインプログラムは、Daemon以外のスレッドが存在しない場合にのみ終了します.すなわち,メインプログラムはすべての非Daemonスレッドが終了するのを待ってから終了し,終了すると自動的にすべてのDaemonスレッドが終了する(乱暴に終了する).
Daemonスレッドの用途:
Daemons 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, we have to keep track of them, and tell them to exit, before our program can completely quit. By setting them as daemon threads, we can let them run and forget about them, and when our program quits, any daemon threads are killed automatically.

Daemonスレッドは、プライマリ・スレッドが実行されている場合にのみ有効であり、他の非Daemonスレッドが終了すると、すべてのDaemonスレッドを自動的に殺すことができます.Daemonスレッドの定義がない場合は、これらのスレッドを手動で追跡し、プログラムが終了する前に手動で終了する必要があります.スレッドをDaemonスレッドに設定すると、実行を放任して忘れることができ、メインプログラムが終了すると、これらのDaemonスレッドは自動的に殺されます.
参考文献
  • docs.python.org/2.7
  • Multithreading - Daemon