1 回答
TA贡献1804条经验 获得超2个赞
是的,看起来将管理器创建为全局会导致 Windows 上出现问题。将其移至模块 main 并将命名空间作为参数传递。Pool.map() 只允许将一个参数传递给工作线程,因此请将多个参数(包括命名空间)放入一个列表中。将参数列表的列表传递给 Pool.map()。
我可能是错的,但我认为你不应该期望/要求对象 ID 不改变。
from multiprocessing import Pool, Manager
import numpy as np
def func(a):
"""This is a function that we want our processes to call."""
(config, i) = a
# You can modify the Namespace object from anywhere.
config.z = i
print('config is', config)
# And they will still be shared (i.e. same id).
print('id(config) = {:d}'.format(id(config)))
# This main func
def main(config):
"""The main function contain multiprocess.Pool codes."""
# You can add to the Namespace object too.
config.d = 10
config.a = 5.25e6
pool = Pool(1)
pool.map(func, list([config, i] for i in range(20,25)))
pool.close()
pool.join()
if __name__ == "__main__":
# Create manager object in module-level namespace
mgr = Manager()
# Then create a container of things that you want to share to
# processes as Manager.Namespace() object.
config = mgr.Namespace()
# The Namespace object can take various data type
config.a = 1
config.b = '2'
config.c = [1, 2, 3, 4]
# Let's print the config
print(config)
# Now executing main()
main(config)
# Again, you can add or modify the Namesapce object from anywhere.
config.e = np.round(np.random.rand(2,2), 2)
config.f = range(-3, 3)
print(config)
添加回答
举报