Python's daemon thread

Source: Internet
Author: User
Tags thread class

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.