python process返回值_如何恢复传递给multiprocessing.Process的函数的返回值?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 18:44   40   0

此示例演示如何使用multiprocessing.Pipe实例列表从任意数量的进程返回字符串:import multiprocessing

def worker(procnum, send_end):

'''worker function'''

result = str(procnum) + ' represent!'

print result

send_end.send(result)

def main():

jobs = []

pipe_list = []

for i in range(5):

recv_end, send_end = multiprocessing.Pipe(False)

p = multiprocessing.Process(target=worker, args=(i, send_end))

jobs.append(p)

pipe_list.append(recv_end)

p.start()

for proc in jobs:

proc.join()

result_list = [x.recv() for x in pipe_list]

print result_list

if __name__ == '__main__':

main()

输出:0 represent!

1 represent!

2 represent!

3 represent!

4 represent!

['0 represent!', '1 represent!', '2 represent!', '3 represent!', '4 represent!']

此解决方案使用的资源少于使用烟斗

至少一把锁

缓冲器

线烟斗

至少一把锁

看看每种类型的源代码是很有启发性的。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP