首页 > 解决方案 > 父函数未向多进程子进程发送正确的变量

问题描述

我有一个使用多个进程来遍历列表的代码。每个多进程都需要分配一个比前一个高的数字。我用下面的代码重新创建了这个问题,我试图在创建每个多进程后将 1 添加到变量 x 中,但是,1 只是被添加到父函数中。

代码:

import multiprocessing
from multiprocessing import Queue
x=0   
def function(variables,q):
    global x
    a='apple'
    reponse_tools=a,x
    list(map(q.put, response_tools))
    return None
if __name__=='__main__':
    q = multiprocessing.Queue()
    for i in range(3):
        tools = None
        p = multiprocessing.Process(target=function,args=(tools,q))
        p.start()
        print(q.get())#------->>>>>this will print 0 each time
        x+=1
#print(x) ----->>>this will print 3

标签: pythonmultiprocessing

解决方案


如果您使用multiprocessing.Pool实例,代码将如下所示:

import multiprocessing
from functools import partial


def function(variables, x):
    # variables not used, but it could be
    a = 'apple'
    reponse_tools = a, x
    return reponse_tools

if __name__=='__main__':
    # constant tools:
    tools = None
    worker = partial(function, tools) # first argument to function will be tools
    with multiprocessing.Pool() as pool:
        results = pool.map(worker, range(3))
    print(results)

印刷:

[('apple', 0), ('apple', 1), ('apple', 2)]

推荐阅读