Python Glossary Русский

all Python 3multiprocessingfunction

multiprocessing.Pipe()

communication

Creates a pipe of two Connection ends with send() and recv(). It is faster than a queue but meant for exactly two parties.

Syntax

conn1, conn2 = multiprocessing.Pipe(duplex=True)

Pipe(duplex=False) returns a pair (receive-only, send-only), the reading end first, and it is easy to mix them up: recv() on the writing end raises OSError. If two processes read from or write to the same end at once, the data can get corrupted; use Queue for many parties. recv() raises EOFError only once every copy of the other end is closed, so after start() the parent closes its copy of the child's end or it waits forever. The undocumented allow_connection_pickling now only imports multiprocessing.connection — connections pickle across processes anyway.

Examples

import multiprocessing as mp
def child(conn):
    conn.send({'status': 'ok'})
    conn.close()
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    parent_end, child_end = ctx.Pipe()
    p = ctx.Process(target=child, args=(child_end,))
    p.start()
    child_end.close()  # своя копия конца ребёнка не нужна
    print(parent_end.recv())  # → {'status': 'ok'}
    p.join()
import multiprocessing as mp
if __name__ == '__main__':
    reader, writer = mp.Pipe(duplex=False)
    writer.send([1, 2])
    print(reader.recv())  # → [1, 2]
    try:
        writer.recv()
    except OSError as e:
        print(e)  # → connection is write-only
    writer.close()
    try:
        reader.recv()
    except EOFError:
        print('EOF')  # → EOF

See also

Open in the full glossarydocs.python.orgReport an inaccuracy