python 多进程或多进程不工作[EDIT]列表(zip(a,B,))行为

hlswsv35  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(190)

下面的代码

  1. import multiprocessing as mp
  2. from multiprocessing.managers import SyncManager
  3. n_cores = mp.cpu_count()
  4. def parallel_fn(job_n, cache):
  5. cache['job_b'] = job_n
  6. return job_n
  7. if __name__=="__main__":
  8. with SyncManager() as manager:
  9. shared_cache = manager.dict()
  10. args = list(zip(range(n_cores), shared_cache))
  11. with mp.Pool(n_cores) as pool:
  12. result = pool.starmap(parallel_fn, args)
  13. print(result)
  14. print(shared_cache)

字符串
返回

  1. 16
  2. Shared dict before: {}
  3. Pool return: []
  4. Shared dict after: {}


我期望从池中返回16个值,在共享字典中返回16个值,但两者都是空的,有人能帮我吗?

fivyi3re

fivyi3re1#

在这种情况下,多处理是一种转移注意力的方法。如果在定义args之后打印它,您将看到一个空列表。您将需要如下修复zip行以创建元组列表。zip返回两个(或更多)项中较短的一个。在这种情况下,你有一个长度为16的range对象和一个长度为0的ProxyDict对象(开始时是空的)。作为一个小例子,看看:list(zip([1, 2], dict())),它返回一个长度为0的列表。
另外,我猜您希望将job_n作为名称放入该高速缓存字典中。

  1. import multiprocessing as mp
  2. from multiprocessing.managers import SyncManager
  3. n_cores = mp.cpu_count()
  4. def parallel_fn(job_n, cache):
  5. # Change 'job_b' to job_n
  6. cache[job_n] = job_n
  7. return job_n
  8. if __name__=="__main__":
  9. with SyncManager() as manager:
  10. shared_cache = manager.dict()
  11. # Create a list of tuples to use as args in starmap
  12. args = [(n, shared_cache) for n in range(n_cores)]
  13. with mp.Pool(n_cores) as pool:
  14. result = pool.starmap(parallel_fn, args)
  15. print(result)
  16. print(shared_cache)

字符串
在我的8核机器上,输出是:

  1. [0, 1, 2, 3, 4, 5, 6, 7]
  2. {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7}

展开查看全部

相关问题