First, the way the process is opened
Using modules to open processes
1 fromMultiprocessingImportProcess2 ImportTime,random3 ImportOS4 defPiao (name):5 Print(Os.getppid (), Os.getpid ())6 Print('%s is piaoing'%name)7 #Time.sleep (Random.randint (1,3))8 Print('%s is Piao end'%name)9 if __name__=='__main__':TenP1=process (target=piao,kwargs={'name':'Alex',}) OneP2=process (target=piao,args= ('Wupeiqi',)) AP3=process (target=piao,kwargs={'name':'Yuanhao',}) - P1.start () - P2.start () the P3.start () - Print('Main Process', Os.getpid ())
Using classes to open processes
1 fromMultiprocessingImportProcess2 ImportTime,random3 ImportOS4 classPiao (Process):5 def __init__(self,name):6Super ().__init__()7Self.name=name8 defRun (self):9 Print(Os.getppid (), Os.getpid ())Ten Print('%s is piaoing'%self.name) One #Time.sleep (Random.randint (1,3)) A Print('%s is Piao end'%self.name) - if __name__=='__main__': -P1=piao ('Alex') theP2=piao ('Wupeiqi') -P3=piao ('Yuanhao') - - P1.start () + P2.start () - P3.start () + Print('Main Process', Os.getpid (), Os.getppid ())
Two, multi-process
Server-side
1 fromSocketImport*2 fromMultiprocessingImportProcess3s=socket (af_inet,sock_stream)4S.setsockopt (sol_socket,so_reuseaddr,1)#That 's it, in front of BIND plus5S.bind (('127.0.0.1', 8088))6S.listen (5)7 defTalk (conn,addr):8 whileTrue:#Communication Cycle9 Try:TenDATA=CONN.RECV (1024) One if notData Break A Conn.send (Data.upper ()) - exceptException: - Break the conn.close () - if __name__=='__main__': - whileTrue:#Link Loops -Conn,addr=s.accept () +P=process (target=talk,args=(CONN,ADDR)) - P.start () +S.close ()
Client
1 fromSocketImport*2C=socket (af_inet,sock_stream)3C.connect (('127.0.0.1', 8088))4 5 whileTrue:6Msg=input ('>>:'). Strip ()7 if notMsgContinue8C.send (Msg.encode ('Utf-8'))9DATA=C.RECV (1024)Ten Print(Data.decode ('Utf-8')) OneC.close ()
Python concurrent programming Multi-process (i): Process open mode & multi-process