python之daemon线程

[python之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 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.

  Function: isDaemon ( ),  setDaemon ()
  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.
  
  要点: 当无活跃的非daemon线程时, 当前python程序会退出. 突然退出的daemon不会释放资源(打开的文件,数据库操作). 所以建议使用非Daemon线程,使用Event这种信号机制来退出程序.
  
  参考官方文档: http://docs.python.org/2.7/library/threading.html#thread-objects

你可能感兴趣的:(python)