Answer the question
In order to leave comments, you need to log in
How to implement bidirectional messaging between processes?
How to implement bidirectional messaging between parent and child process in multiprocessing
python library?
The documentation says that it duplex
should be equal True
for bidirectional exchange, but there is no code how it should look like. I suppose that it is necessary to foo
add a message handler to the function as at the end of the code, but it somehow works crookedly for me, the code does not complete the work.
import time, random
from multiprocessing import Process, Pipe, current_process
from multiprocessing.connection import wait
def foo(w):
for i in range(10):
w.send((i, current_process().name))
w.close()
if __name__ == '__main__':
readers = []
for i in range(4):
r, w = Pipe(duplex=False)
readers.append(r)
p = Process(target=foo, args=(w,))
p.start()
w.close()
while readers:
for r in wait(readers):
try:
msg = r.recv()
except EOFError:
readers.remove(r)
else:
print(msg)
import time, random
from multiprocessing import Process, Pipe, current_process
from multiprocessing.connection import wait
def foo(w, i):
readers2 = []
readers2.append(w)
w.send((i, "Child"))
while readers2:
for r2 in wait(readers2):
try:
msg = r2.recv()
except EOFError:
readers2.remove(r2)
else:
print("Child: " + msg)
w.close()
if __name__ == '__main__':
readers = []
for i in range(1):
r, w = Pipe(duplex=True)
readers.append(r)
p = Process(target=foo, args=(w,i))
p.start()
w.close()
while readers:
for r in wait(readers):
try:
msg = r.recv()
r.send("test_1")
r.send("test_2")
except EOFError:
readers.remove(r)
else:
print(msg)
r.close()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question