【问题标题】:Using shared array in multiprocessing在多处理中使用共享数组
【发布时间】:2019-10-09 17:59:33
【问题描述】:

我正在尝试在 python 中运行一个并行进程,其中我必须根据某些条件从一个大数组中提取某些多边形。大数组有 10k+ 个被索引的多边形。

extract_polygon 函数中,我传递了(数组、索引)。根据索引,函数必须返回与该索引对应的多边形,或者不根据定义的条件返回。该数组永远不会更改,仅用于根据提供的索引读取多边形。

由于数组非常大,我在并行处理过程中遇到了内存不足的错误。我怎样才能避免这种情况? (在某种程度上,如何在多处理中有效地使用共享数组?)

下面是我的示例代码:

def extract_polygon(array, index):

    try:
        islays = ndimage.find_objects(clone==index)
        poly = clone[islays[0][0],islays[0][1]]
        area = np.count_nonzero(ploy)        

        minArea = 100
        maxArea = 10000

        if (area > minArea) and (area < maxArea):
            return poly
        else:
            return None

    except:
        return None

start = time.time()
pool = mp.Pool(10)
results = pool.starmap(get_objects,[(array, index) for index in indices])
pool.close()
pool.join()

#indices here is a list of all the indexes we have. 

在这种情况下,我可以使用像 ray 这样的任何其他库吗?

【问题讨论】:

    标签: python multithreading ray


    【解决方案1】:

    您绝对可以使用像 Ray 这样的库。

    结构看起来像这样(简化以删除您的应用程序逻辑)。

    import numpy as np
    import ray
    
    ray.init()
    
    # Create the array and store it in shared memory once.
    array = np.ones(10**6)
    array_id = ray.put(array)
    
    
    @ray.remote
    def extract_polygon(array, index):
        # Change this to actual extract the polygon.
        return index
    
    # Start 10 tasks that each take in the ID of the array in shared memory.
    # These tasks execute in parallel (assuming there are enough CPU resources).
    result_ids = [extract_polygon.remote(array_id, i) for i in range(10)]
    
    # Fetch the results.
    results = ray.get(result_ids)
    

    您可以在documentation 中阅读有关 Ray 的更多信息。

    请参阅下面的一些相关答案:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 2023-03-10
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      相关资源
      最近更新 更多