python - 父函数未向多进程子进程发送正确的变量
问题描述
我有一个使用多个进程来遍历列表的代码。每个多进程都需要分配一个比前一个高的数字。我用下面的代码重新创建了这个问题,我试图在创建每个多进程后将 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
解决方案
如果您使用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)]
推荐阅读
- lisp - 为什么“让”添加换行符?(我可以摆脱它吗?)
- python - 为什么 pandas excel writer 不会写入我的文件路径?
- python - 通过在 python 中使用它的字符串名称创建一个类的实例
- swift - 访问最近存储的文件(文件“插入文件”无法打开,因为没有这样的文件)
- php - 如何为每个在 Apache 上注册 PHP 的用户添加子域?
- python - Python - 多处理从子目录读取文件并创建 csv 文件列表输出
- google-cloud-platform - 在 GCP 中的组织内共享自定义图像
- node.js - 上传具有多个文件字段的多个图像
- javascript - 为什么我的获取顺序会改变程序的工作方式?
- c# - 从另一个包创建一个类的实例