S
S
Space Around2020-10-07 14:37:14
Python
Space Around, 2020-10-07 14:37:14

How to implement bidirectional messaging between processes?

How to implement bidirectional messaging between parent and child process in multiprocessingpython library?
The documentation says that it duplexshould be equal Truefor bidirectional exchange, but there is no code how it should look like. I suppose that it is necessary to fooadd 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.

Unidirectional exchange code:
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)

The code of my bidirectional exchange implementation
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

1 answer(s)
J
javedimka, 2020-10-07
@javedimka

Just do two turns. Why complicate things.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question