​Python的multiprocessing的Process怎么获取子进程的函数返回值?

2020-04-09 17:09发布

from multiprocessing import Processdef func(x,y):print(x*y)return x + y#新建一个进程if __name__ == '__...

from multiprocessing import Process
def func(x,y):
print(x*y)
return x + y

#新建一个进程
if __name__ == '__main__':
P = Process(target = func ,args = (2,3))
print(P.start())
P.join()
P.close()

上面这段代码,执行之后只能打出 x*y的值,而x+y获取不到,怎么获取子进程执行的fn函数的返回值呢?

2条回答
老易
2021-11-11 16:24

你好,下面是一个用process带返回值的例子。主要是需要用pipe来做
from multiprocessing import Process, Pipe
SENTINEL = 'SENTINEL'
def sim_busy(write_conn, x):
for _ in range(int(x)):
assert 1 == 1
result = x
write_conn.send(result)
# If all results are send, send a sentinel-value to let the parent know
# no more results will come.
write_conn.send(SENTINEL)
if __name__ == '__main__':
# duplex=False because we just need one-way communication in this case.
read_conn, write_conn = Pipe(duplex=False)
p = Process(target=sim_busy, args=(write_conn, 150e6)) # 150e6 == 150000000.0
p.start()
for result in iter(read_conn.recv, SENTINEL): # sentinel breaks the loop
print(result)

一周热门 更多>