Yesterday encountered a problem in a Python program opened three threads polling processing three things, just start all right, but in the afternoon, found that one of the threads died, only two other threads are running, this time do not want to interrupt the main process, It also requires that the system automatically starts a dead thread and remembers to do a daemon to monitor whether three working threads are working properly.
I checked the manual. The Python threading thread class provides the following methods:
- run (): the method used to represent thread activity.
- Start (): initiates thread activity.
- join ([TIME]): waits until the thread aborts. This blocks the calling thread until the thread's join () method is called abort-gracefully exits or throws an unhandled exception-or an optional timeout occurs.
- isAlive (): Returns whether the thread is active.
- getName (): returns the thread name.
- setName (): sets the thread name.
This allows you to use the IsAlive () method within the daemon to determine if the worker thread is alive, and if it is dead, re-establish a worker thread and start it up (note that it is not possible to use the original thread to start (), because the thread has ended and the in-memory instance has been freed. So use this method will be error) below is the code of monitoring
#coding =utf-8import timefrom Threading Import threadclass Ticker (THREAD):D EF Run (self): while True:print time.time () if ( Time.time () > 1470883000): Breakpasstime.sleep (3) Passpassclass moniter (Thread):d EF Run (self): while True:global Tif (T.isalive ()):p rint ' t is alive ' else:p rint ' is dead ' t = ticker () T.start () print ' Checking ' time.sleep (5) passpasst = tick ER () t.start () mo = Moniter () Mo.start ()
Python's daemon thread