Implementation of process multi-processes by means of inheritance
1 fromMultiprocessingImportProcess2 Import Time3 4 classmynewprocess (Process):5 defRun (self):6 forIinchRange (10):7 Print("----Run----")8Time.sleep (1)9 Ten One if __name__=="__main__": Ap =mynewprocess () - -P.start ()#the Start method in process actively calls the Run method the forIinchRange (10):Print("---main---") Time.sleep (1)
Pool process pooling for multi-process
1 Import Time2 fromMultiprocessingImportPool3 4 defworker ():5 forIinchRange (10):6 Print("From worker%s"%i)7Time.sleep (0.5)8 9 deffoo ():Ten forIinchRange (10): One Print("From foo%s"%i) ATime.sleep (0.5) - - defBar (): the forIinchRange (10): - Print("From Bar%s"%i) -Time.sleep (0.5) - + if __name__=="__main__": -Pool = Pool (3)#Create three processes + Pool.apply_async (worker) A Pool.apply_async (foo) at Pool.apply_async (BAR) - -Pool.close ()#Close Process pool, prohibit Add task -Pool.join ()#wait for the child process to finish before the main process goes down - Print("IS-done ...") - in - to #the process and Pool are finally called Fork + #Typically, half of the main process is used to wait for low ah,,, real tasks in the child process to execute
Use pool process pools for simple file copying
1 ImportOS2 Import Time3 fromMultiprocessingImportPool4 5 defcopyFile (OldPath, NewPath, fileName):6 Print("%s ready to replicate in ... "%fileName)7With open ("%s\%s"% (OldPath, fileName),'R') as FR, open ("%s\%s"% (NewPath, fileName),'W') as FW:8 forLineinchfr:9 Fw.write (line)TenTime.sleep (1) One A - if __name__=="__main__": -OldPath = R"file" theNewPath = R"file-Copy" - - Os.mkdir (NewPath) - +Pool = Pool (5) - +FileList =Os.listdir (OldPath) A at forFileNameinchfileList: - Pool.apply_async (CopyFile, (OldPath, NewPath, fileName)) - - pool.close () - - Pool.join () in - Print("File copy complete....")
0704 process inheritance enables multi-process, pool process pools, and pool to implement multi-process replication files