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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.