python 多核并行计算 示例3,使用 管道 Pipe(仅仅作为记录)

import multiprocessing as mul

# 管道 Pipe:
# Pipe可以是单向(half-duplex),也可以是双向(duplex)。
# 通过mutiprocessing.Pipe(duplex=False)创建单向管道 (默认为双向)。
# 一个进程从PIPE一端输入对象,然后被PIPE另一端的进程接收,
# 单向管道只允许管道一端的进程输入,而双向管道则允许从两端输入。

def proc1(pipe):
    pipe.send('hello')
    print('proc1 rec:', pipe.recv())


def proc2(pipe):
    print('proc2 rec:', pipe.recv())
    pipe.send('hello, too')


# Build a pipe
pipe = mul.Pipe()

if __name__ == '__main__':
    # Pass an end of the pipe to process 1
    p1 = mul.Process(target=proc1, args=(pipe[0],))
    # Pass the other end of the pipe to process 2
    p2 = mul.Process(target=proc2, args=(pipe[1],))

    # 非阻塞函数
    p1.start()
    p2.start()

    # 阻塞函数
    p1.join()
    p2.join()

 

posted @ 2021-09-06 15:52  土博姜山山  阅读(160)  评论(0编辑  收藏  举报