我有一个代码,使用多进程去通过一个列表。每个多进程需要分配一个比前一个高1的数字。我用下面的代码重新创建了这个问题,我试图在每个多进程创建后向变量x添加1,但是,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
如果您使用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)]