Reputation: 125
I am new to coding. Want to know if a Pipe() can be used multiple times for Inter Process Communication. If yes, what am I missing in the following code? If no, then what is the reason that one pipe cannot be used more than once.
import multiprocessing
def f1(pipe):
r, w = pipe
r.close()
for n in range(10):
w.send(n)
def f2(pipe):
r, w = pipe
w.close()
while True:
try:
item = r.recv()
except EOFError:
break
print("Item received by f2:", item)
def f3(pipe):
r, w = pipe
r.close()
for n in range(10, 21):
w.send(n)
def f4(pipe):
r, w = pipe
w.close()
while True:
try:
item = r.recv()
except EOFError:
break
print("Item received by f2:", item)
if __name__ == '__main__':
(r, w) = multiprocessing.Pipe()
p1 = multiprocessing.Process(target=f1, args=((r, w),))
p2 = multiprocessing.Process(target=f2, args=((r, w),))
p1.start()
p2.start()
w.close()
p1.join()
p2.join()
#(r, w) = multiprocessing.Pipe()
p3 = multiprocessing.Process(target=f3, args=((r, w),))
p4 = multiprocessing.Process(target=f4, args=((r, w),))
p3.start()
p4.start()
w.close()
p3.join()
p4.join()
Upvotes: 1
Views: 517
Reputation: 38
In case you haven't figured it out by now, the problem is you are closing both connection objects (what you called "r" and "w"). Once you close them you cannot use them anymore. Just comment out the close statements and it should be working. If you want to manually close them do so after all the join statements.
I would also change in f2:
while r.poll(1):
try:
...
That way it will exit the loop if it doesn't receive data for longer than a second.
Upvotes: 2