1. Process
the class that created the process: Processes ([group [, Target [, name [, args [, Kwargs]]]),target represents the calling object,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.
methods : Is_alive (), join ([timeout]), run (), start (), Terminate (). Wherein, process starts a session with start ().
Properties : Authkey, Daemon (to be set through Start (), ExitCode (the process is none at run time, if it is –n, signal N ends), name, PID. Where daemon is automatically terminated after the parent process terminates and cannot produce a new process, it must be set before start ().
Example 1.1: Create a function and use it as a single process
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 = (1,)) #target表示调用对象, args incoming call object's parameter tuple # P.start ()Print("P.pid:", P.pid)Print("P.name:", P.name)Print("p.is_alive:", P.is_alive ())
Results:
p.pid:8736p.name:process-1 is Tue Apr 20:55:12 are Tue Apr 21 20:55:1 5 is Tue Apr 20:55:18 are Tue Apr 20:55:21 is Tue APR 21 20:55:24 2015
Example 1.2: Create a function and use it as multiple processes
ImportMultiprocessingImport Timedefworker_1 (interval):Print("worker_1") Time.sleep (interval)Print("End worker_1")defworker_2 (interval):Print("worker_2") Time.sleep (interval)Print("End Worker_2")defworker_3 (interval):Print("worker_3") Time.sleep (interval)Print("End Worker_3")if __name__=="__main__": P1= multiprocessing. Process (target = worker_1, args = (2,)) P2= multiprocessing. Process (target = worker_2, args = (3,)) P3= multiprocessing. Process (target = worker_3, args = (4,)) P1.start () P2.start () P3.start ( )Print("The number of the CPU is:"+Str (Multiprocessing.cpu_count ())) forPinchMultiprocessing.active_children ():Print("Child P.name:"+ P.name +"\tp.id"+str (p.pid))Print("END!!!!!!!!!!!!!!!!!")
Results:
is: 4child p.name:process-3 p.id7992child p.name:process-2 p.id4204child p.name:process-1 p.id6380end!!!!!!!!!!!!!!!!! Worker_1worker_3worker_2end worker_1end worker_2end worker_3
Example 1.3: Defining a process as a class
ImportMultiprocessingImport Timeclassclockprocess (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= Clockprocess (3) P.start ()
Python multi-process programming