Multi-process pipe

pipe module can achieve data transfer between processes

Chestnut 1: 3 process, a main process, sub-process 2, three pipes, connected by three processes pipe 3, the main process send a message by forwarding sub-process 2, and finally return to the main process output

import multiprocessing

def func(pipe_end,pipe_head):
    msg = pipe_end.recv()
    print("--->",msg)
    pipe_head.send(msg)



if __name__ == '__main__':
    pipe_head_1, pipe_end_1 = multiprocessing.Pipe () # Statement of the pipe. 1 
    pipe_head_2, pipe_end_2 multiprocessing.Pipe = () # Statement of the pipe 2 
    pipe_head_3, pipe_end_3 multiprocessing.Pipe = () # Statement of conduit. 3 

    P1 = multiprocessing.Process (target = func, args = (pipe_end_1, pipe_head_2)) # subprocess execution p1 function func, parameters for the pipe ends 
    p1.start ()
    p2 = multiprocessing.Process (target = func, args = (pipe_end_2, pipe_head_3)) # subprocess execution p2 function func, parameters for the pipe ends 
    p2.start ()
    pipe_head_1.send("hello")
    print(pipe_end_3.recv())

 

Chestnut 2: 3 process, a main process, a subprocess, a grandchild processes, three processes connected by pipe 3, the main process send a message by forwarding sub-process 2, and finally return to the main process output

import multiprocessing

def func(pipe_end,pipe_head,*args):
    #print("--->",args[0])
    #print('--->',args[1])
    msg = pipe_end.recv()
    print("-->",msg)
    pipe_head.send(msg)
    p2 = multiprocessing.Process (target = func2, args = (args [0], args [. 1])) # subprocess execution p2 function func2, parameters for the pipe ends 
    p2.start ()

def func2(pipe_end,pipe_head):
    msg = pipe_end.recv()
    print("--->",msg)
    pipe_head.send(msg)



if __name__ == '__main__':
    pipe_head_1, pipe_end_1 = multiprocessing.Pipe () # Statement of the pipe. 1 
    pipe_head_2, pipe_end_2 multiprocessing.Pipe = () # Statement of the pipe 2 
    pipe_head_3, pipe_end_3 multiprocessing.Pipe = () # Statement of conduit. 3 
    # Print (pipe_end_2) 
    # Print ( pipe_head_3) 

    p1 = multiprocessing.Process (target = func, args = (pipe_end_1, pipe_head_2, pipe_end_2, pipe_head_3)) # subprocess execution p1 function func, parameters for the pipe ends 
    p1.start ()

    pipe_head_1.send("hello")
    print("->",pipe_end_3.recv())

Guess you like

Origin www.cnblogs.com/goldtree358/p/12133700.html