首页 > 解决方案 > Why can a parent send data only once in a bidirectional channel?

问题描述

The child process can send as much data as it wants, but the parent process can send it once, then the program stops and waits for something (i don't know what). The channel is open, i can't understand why it happen... I have already looked at the documentation, but there is no example in bidirectional channel, only unidirectional channel.

Code:

from multiprocessing import Process, Pipe, current_process
from multiprocessing.connection import wait

def foo(w, i):
    print("w -> 1234")
    w.send("1234")

    readers = []

    readers.append(w)

    while readers:
        for r in wait(readers):
            try:
                msg = r.recv()
            except EOFError:
                print("w: error")
                readers.remove(r)
            else:

                if(msg == "1234"):
                    w.send("4321")
                    print("1234 -> w -> 4321")

                if(msg == "4321"):
                    print("4321 -> w")
                    print("w: close")


if __name__ == '__main__':

    readers = []
    r, w = Pipe(duplex=True)
    readers.append(r)
    p = Process(target=foo, args=(w, 1))
    p.start()
    w.close()

    while readers:
        for r in wait(readers):
            try:
                msg = r.recv()
                if(msg == "1234"):
                    r.send("1234")
                    print("1234 -> r -> 1234")

                if(msg == "4321"):
                    r.send("r: 4321")
                    print("4321 -> r -> 4321")

            except EOFError:
                print("r: error")
                readers.remove(r)

Current output:

w -> 1234
1234 -> r -> 1234
1234 -> w -> 4321
4321 -> r -> 4321

Expected output:

w -> 1234
1234 -> r -> 1234
1234 -> w -> 4321
4321 -> r -> 4321
4321 -> w
w: close

标签: pythonpython-3.xmultithreadingmultiprocessingpython-multiprocessing

解决方案


推荐阅读