1

I have two processes: proc_a, proc_b and I want the return of proc_a to be equal to the value of data_new. Is this possible or do I have to use multiple Pipes?

if __name__ == '__main__':

    parent, child = Pipe()
    p1 = Process(target=proc_a, args=(parent, child,))
    p2 = Process(target=proc_b, args=(parent, child,))

    p1.start()
    p2.start()
    p1.join()
    p2.join()

And on proc_a() and proc_b():

def proc_a(parent, child):
        data = somedata
        child.send(data)
        result = parent.recv()

        return result


def proc_b(parent, child):
    data = parent.recv()
    data_new = data + 1 # Sample change 
    child.send(data_new)
user3807593
  • 42
  • 1
  • 7

1 Answers1

2

You can solve it with only one pipe, as pipes are two way (duplex). But what you can't do is to send both ends of the pipes to both processes.

See this section of the docs:

Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.

This code works and prints 2:

from multiprocessing import Pipe, Process

def proc_a(pipe):
    data = 1
    pipe.send(data)
    result = pipe.recv()
    print(result)

def proc_b(pipe):
    data = pipe.recv()
    data_new = data + 1 # Sample change 
    pipe.send(data_new)

if __name__ == '__main__':
    parent, child = Pipe()
    p1 = Process(target=proc_a, args=(parent,))
    p2 = Process(target=proc_b, args=(child,))

    p1.start()
    p2.start()
    p1.join()
    p2.join()

Note that return of proc_a does nothing, if you need to consume the return value in the parent process have a look at this question

Community
  • 1
  • 1
hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • Can the parent close the connection to unblock the "pipe.recv()" in each process? Also here there is no assymetry between processes so I would be very finicky and call them "conn_a" and "conn_b" instead of "parent, child" for instance, which are more suited when the main process spawns 1 or more subprocesses – Eric Burel Dec 09 '22 at 10:58