Import Time fromMultiprocessingImportProcess,queuemsg_queue= Queue (5)defStarta (msgqueue): whileTrue:ifMsgqueue.empty () >0:Print 'queue is empty%d'%(Msgqueue.qsize ())Else: Msg=Msgqueue.get ()Print 'Get msg%s'%(msg,) Time.sleep (1)defSTARTB (msgqueue): whileTrue:msgQueue.put ('Hello World') Print 'put Hello World queue size is%d'%(Msgqueue.qsize (),) Time.sleep (3)if __name__=='__main__': Processa= Process (target=starta,args=(Msg_queue,)) PROCESSB= Process (target=startb,args=(Msg_queue,)) Processa.start ()Print 'Processa start .'Processb.start ()Print 'PROCESSB start .'
python2.6 test.py Processa start. Queue is empty 0processB start. Put Hello World queue size is 1get msg Hello worldqueue are empty 0queue is empty 0put Hello World queue size is 1get msg h Ello Worldqueue is empty 0queue was empty 0put Hello World queue size is 1get msg Hello Worldqueue was empty 0queue is empty 0put Hello World Queue size is 1get msg Hello worldqueue are empty 0queue is empty 0put Hello World queue size is 1get msg Hello Worldqueue is empty 0queue are empty 0put Hello World queue size is 1get msg Hello worldqueue are empty 0queue is EMP Ty 0put Hello World queue size is 1get msg Hello worldqueue are empty 0queue is empty 0
The main process defines a type of queue variable and passes it as the args parameter of the process to the subprocess Processa and PROCESSB, two processes one to write to the queue, and one to read the data.
The results of the printing are as follows:
python2.6 test.py Processa start. Queue is empty 0processB start. Put Hello World queue size is 1get msg Hello worldqueue are empty 0queue is empty 0put Hello World queue size is 1get msg h Ello Worldqueue is empty 0queue was empty 0put Hello World queue size is 1get msg Hello Worldqueue was empty 0queue is empty 0put Hello World Queue size is 1get msg Hello worldqueue are empty 0queue is empty 0put Hello World queue size is 1get msg Hello Worldqueue is empty 0queue are empty 0put Hello World queue size is 1get msg Hello worldqueue are empty 0queue is EMP Ty 0put Hello World queue size is 1get msg Hello worldqueue are empty 0queue is empty 0
Example of Python multi-process using queue communication