Control the python program running for a certain period of time through threads
Import time
Class Test (threading. thread): def _ init _ (self, para): # initialize the threading parameter. thread. _ init _ (self) self. para = para def run (self): while (True): doMail (self. para) # collect if _ name _ = "_ main _": para = "" while True: msg = Test (para) msg. setDaemon (True) msg. start () msg. join (2) time. sleep (2)
In the above example, the thread is used for collection, and the thread is started cyclically in the process. The thread is killed every two seconds, and a new thread is restarted for collection.
In python, some thread mechanisms are different from those in C/C ++: in C/C ++, when the main thread ends, its subthreads are killed by the main thread by default. In python, after the main thread ends, the main thread exits after the child thread ends by default.
Python has two functions for thread management: join and setDaemon.
- Join: If threada. join () is called in thread B, thread B will run threada. join () later after threada is finished.
- SetDaemon: main thread A starts sub-thread B and calls B. setDaemaon (True): When the main thread ends, the sub-thread B is also killed, which is the same as the default effect in C/C ++.