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)
添加回答
舉報