gpt4 book ai didi

Python - 对多个进程使用相同的双工 Pipe()

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:13 24 4
gpt4 key购买 nike

我有两个进程:proc_a、proc_b,我希望 proc_a返回等于data_new 的值。这是可能的还是我必须使用多个管道?

if __name__ == '__main__':

parent, child = Pipe()
p1 = Process(target=proc_a, args=(parent, child,))
p2 = Process(target=proc_b, args=(parent, child,))

p1.start()
p2.start()
p1.join()
p2.join()

关于 proc_a()proc_b():

def proc_a(parent, child):
data = somedata
child.send(data)
result = parent.recv()

return result


def proc_b(parent, child):
data = parent.recv()
data_new = data + 1 # Sample change
child.send(data_new)

最佳答案

您只需一根管道即可解决此问题,因为管道是双向的(双工)。但你不能做的就是将管道的两端都发送到两个进程。

查看此section of the docs :

Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.

此代码有效并打印 2:

from multiprocessing import Pipe, Process

def proc_a(pipe):
data = 1
pipe.send(data)
result = pipe.recv()
print(result)

def proc_b(pipe):
data = pipe.recv()
data_new = data + 1 # Sample change
pipe.send(data_new)

if __name__ == '__main__':
parent, child = Pipe()
p1 = Process(target=proc_a, args=(parent,))
p2 = Process(target=proc_b, args=(child,))

p1.start()
p2.start()
p1.join()
p2.join()

请注意,proc_areturn 不执行任何操作,如果您需要在父进程中使用返回值,请查看 this question

关于Python - 对多个进程使用相同的双工 Pipe(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41812526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com