即使使用Manager.list(),也不会将值添加到使用多处理池的列表中



在下面的代码中可以看到,我正在生成一个带有管理器和列表推导式的多处理来处理池:

import multiprocessing
def foo(name,archive):
print('hello ', name)
archive.append('hello ', name)
def main():
max_process = multiprocessing.cpu_count()-1 or 1
pool = multiprocessing.Pool(max_process)
manager = multiprocessing.Manager()
archive = manager.list()
[pool.apply_async(foo, args=[name,archive]) for name in range(0, 10)]
pool.close()
pool.join()
print(archive)
if __name__ == '__main__':
main()

但是附件仍然没有被放在经理设计的列表中:

hello  0
hello  4
hello  5
hello  7
hello  1
hello  6
hello  8
hello  3
hello  9
hello  2
[]

我该如何着手解决这个问题?

尝试将archive.append('hello ', name)更改为:

archive.append(f"hello {name}")

那么结果是:

hello  0
hello  5
hello  1
hello  9
hello  6
hello  3
hello  7
hello  8
hello  2
hello  4
['hello 0', 'hello 5', 'hello 1', 'hello 6', 'hello 9', 'hello 7', 'hello 3', 'hello 8', 'hello 2', 'hello 4']

最新更新