1. Create a process with fork (used in Linux)
1 ImportOS2 #fork function, only shipped on UNIX/LINUX/MAC, Windows can not3PID =os.fork ()4 ifPID = =0:5 Print(' hello--1')6 Else:7 Print(' hello--2')
When the program goes to Os.fork (), it creates a child process and copies all the information from the parent process to the child process, and the parent and child processes get a return value from Os.fork (), which is 0 in the child process, and the return value in the parent process is the ID number of the child process.
Note: When fork is called, it returns two values, one representing 0 of the child process, and the other is the child process ID number representing the parent process.
The execution order of parent and child processes is not regular and depends entirely on the scheduling algorithm of the system
Get process ID Number: Gets the process ID number of the current process: Getpid () Gets the process ID number of the parent process: Getppid ()effects of multiple processes on global variables:multi-process, all data for each process has one copy (including global variables), unaffected
Mainly because the essence of the multi-process is that each process takes a turn at each core of the CPU, and each time there is only one process on each core of the CPU
2. Use multiprocessing to create multiple processes
1 fromMultiprocessingImport*2 ImportOS3 4 defrun_process (num):5 Print("Child process%d--->%d its parent process--->%d"%(Num,os.getpid (), Os.getppid ()))6 7 defMain ():8 #get started with 5 of processes9 forNuminchRange (5):Ten #The parameters commonly used in process are target, args, Kwargs, name where name means an alias to the process, and if the name parameter is not written, the default is name = Process-n N is an incrementing integer Onep = Process (target=run_process,args=(num,)) A P.start () - #the role of P.join () join () is to wait for the child process to end and then go down, usually for inter-process synchronization - #the Join (timeout) join () can accept a time-out parameter to determine how many seconds it will wait the - if __name__=="__main__": -Main ()The results of its operation are as follows:
Running results The number of the child processes does not follow the order of the 0,1,2,3,4 in the for loop because the run of the subprocess is not sequential, it depends on the scheduling algorithm of the system
3. Create a process from a subclass of process
1 fromMultiprocessingImportProcess2 ImportOS3 4 #Create a subclass of a process5 classProcess_children (process):6 def __init__(self, num):7 #this is mainly because there are __init__ methods in the Process class.8 #It 's the equivalent of rewriting the __init__ method if you don't write this sentence, but that's not what we want.9 #The function of this sentence is to pass the parameters received in the subclass to the process parent class .TenProcess.__init__(self) OneSelf.num =Num A - #This run method must be defined and written as run, because the code in this function determines how the child process is created - defRun (self): the Print("%s---> The current process ID is%s and the parent process is%s"%(Self.num, Os.getpid (), Os.getppid ())) - - defMain (): - whileTrue: + forNuminchRange (5): - #If we create a process with a subclass of process, we can simply pass the parameters that need to be passed to the class. +p =process_children (num) A P.start () at #P.join () - - if __name__=="__main__": -Main ()
4. Process pool (code tested under Ubuntu)
1 fromMultiprocessingImportPool2 ImportOS3 4 deffunc (num):5 Print("%d---> The current process is:%d, its parent process is:%d"%(num, Os.getpid (), Os.getppid ()))6 7 #open a process pool, the maximum number of processes in the pool is 38 #the maximum number of processes means that the maximum number of processes in this process pool at the time of unification is 39 #A new process is created for the waiting process if there is a process end in the process poolTenPo=pool (3) One A defMain (): - forIinchRange (0,10): - #Apply_async for non-blocking mode apply as blocking mode thePo.apply_async (func, args=(i,)) - Print("Start") - #close must be placed in front of the join - po.close () + #join is for the main process to wait for the child process to finish executing - Po.join () + Print("Finish") A at if __name__=="__main__": -Main ()Operation Result:
Important: The last Close () must be written in front of join ()
5. Inter-process communication------Queue queue: First In first Out (FIFO)---------pre-in and out stack: First in last Out (FILO)----------
Queue usage: q = queue (num) num indicates the maximum length of the queue
Write: Q.put (value), q.put_nowait () read: Q.get (), q.get_nowait ()
Judgment: Q.full (), Q.empty (), Q.qsize ()
Q.get ([block[timeout]])
1> can use queue to pass data between two processes, one process queue.put (), another process queue.get () 2> interprocess communication in the process pool needs to be imported multiprocessing Manager:from Multiprocessing Impor Manager,pool and queue in Manager () is required to use the queue, otherwise an error will be----------> q = Manager (). Queue ()
Python Multi-process