首页 > 解决方案 > 您能否分享一些关于在使用多处理时处理列表的见解?(给出一个场景)

问题描述

设想

我有一个 longlist其中每个元素都是 a string,现在我想通过使用一些函数对每个元素执行相同的操作。考虑到list的长度,我想用它multiprocessing来创建一些Process来处理它list。每个Process只处理列表的一部分元素。以这种方式节省时间。

在下面的代码中:

  1. 我创建一个multiprocessing.Manager以使我ls可以在 2 个子进程之间共享。
  2. 然后我创建一个multiprocessing.Pool,希望创建两个进程。一个Processfunc()ls[0:100000]另一个func()ls[100000:200000]
  3. my_operation()on的每个结果ls[index]都是就地写入的。

示例代码(使用2 个进程):

from multiprocessing import Pool, Manager

# len(ls) = 200000
ls = ['a', 'b', ...]  

# Each element of the scopes below is the scope to be processed by the process. 
# (I want to use 2 processes in this example)
scopes = [ (0, 100000), (100000, 200000) ]  

m = Manager()
ls = m.list(ls)  # create a shared list for child processes


def func(range_start, range_end):
    for index in range(range_start, range_end):
        ls[index] = my_operation(ls[index])

def my_operation(str):
    return str

with Pool(2) as pool:
    pool.starmap_async(func, scopes)
    pool.close()
    pool.join()

问题

  1. multiprocessing用于处理此列表的不同范围时,在同一个列表上读取和写入是一个好主意吗?
  2. 如何改进我的代码?(更改Manager为其他内容?较少的共享状态以及如何实现?...)

谢谢!

标签: pythonpython-3.xpython-multiprocessing

解决方案


推荐阅读