Python Multi-process
I. Creating a multi-process approach to the Basic Law
the class that created the process: Processes ([group [, Target [, name [, args [, Kwargs]]]), target represents the calling object, and args represents the positional parameter tuple of the calling object. The Kwargs represents the dictionary of the calling object. Name is an alias. Group is not actually used.
1. Create multi-threading using off-the-shelf process classes
ImportMultiprocessingImport TimedefWorker (interval): N= 5 whilen >0:Print("The time is {0}". Format (Time.ctime ())) Time.sleep (interval) n-= 1if __name__=="__main__": P= multiprocessing. Process (target = worker, args = (3,)) P.start ()Print "P.pid:", P.pidPrint "P.name:", P.namePrint "p.is_alive:", P.is_alive ()
Output: p.pid:8736p.name:process-1p.is_alive:truethe time is Tue April 20:55:12 2015The time is Tue Apr 20:55:15 2015T He time is Tue April 20:55:18 2015The time is Tue April 20:55:21 2015The time is Tue Apr 21 20:55:24 2015
Ii. creating multithreading with a custom class
ImportMultiprocessingImport Timeclassmyprocess (multiprocessing. Process):def __init__(self, interval): multiprocessing. Process.__init__(self) self.interval=intervaldefRun (self): n= 5 whilen >0:Print("The time is {0}". Format (Time.ctime ())) Time.sleep (self.interval) n-= 1if __name__=='__main__': P= Myprocess (3) P.start ()
Output: The time is Wed Jul 22:44:16 2016the time was Wed Jul 22:44:19 2016the time is Wed Jul 22:44:22 2016the Time is Wed Jul 22:44:25 2016the time is Wed Jul 20 22:44:28 2016
Description: A custom multithreaded class needs to override the Run method, which automatically calls the Run method when it executes an instance of the custom class.
3. Guardian Process
1) The daemon is the process of guarding the master process, die with the main process.
2) When the main process exits, the daemon also exits.
3) By default, created by the Forbidden City process, the main process if the execution is complete, and the child process is not completed, the main process will wait for the child process to complete before exiting.
4) The method to set the daemon is Setdaemon = True.
defWorker (interval):Print("Work start:{0}". Format (Time.ctime ())); Time.sleep (interval)Print("Work end:{0}". Format (Time.ctime ()));if __name__=="__main__": P= multiprocessing. Process (target = worker, args = (3,)) P.daemon=True P.start ()Print("end!")
Output Result: end!
Output only one end! , the child process dies as the main process dies, because the daemon is set.
Python Multi-process