带锁的同步numpy 2D数组计数器

时间:2019-04-26 21:07:34

标签: synchronization python-multiprocessing numpy-ndarray

我想并行化在共享的numpy 2D数组上运行的方法。

我的原始应用程序是研究的一部分,非常复杂,但是,我创建了一个玩具示例,从本质上复制了问题。

有一家服装店,出售不同尺寸和颜色的衣服。我以2D矩阵的形式表示了这家商店的库存,其中self.supply_arr[i][j]代表了size icolor j的衣服总数。我有多个客户试图从商店购买。商店出售的衣服不应超过库存。下面,我展示一个非并行的示例。

import numpy as np


class ClothStore(object):
    def __init__(self, num_customers):
        self.supply_arr = np.random.randint(5, size=(2,2))
        self.sold_arr = np.zeros((2,2), dtype=int)
        self.num_customers = num_customers

    def make_purchase(self, size, color):
        left = self.supply_arr[size][color] - self.sold_arr[size][color]
        if left > 0:
            self.sold_arr[size][color] += 1
            return True
        else:
            return False

    def run(self):
        for customer in xrange(self.num_customers):
            size = np.random.randint(2)
            color = np.random.randint(2)

            purchase = self.make_purchase(size, color)

            if purchase:
                print "Customer: {} made successful purchase".format(customer)

if __name__ == "__main__":
    store = ClothStore(100)
    store.run()

    print "Supply Arr: {}".format(store.supply_arr)
    print "Sold Arr: {}".format(store.sold_arr)

我尝试使用run(self)并行化pathos方法,并将self.supply_arr表示为np.empty((2,2), dtype=object),其中每个元素初始化为multiprocessing.Value。但是,我无法使其正常运行。任何帮助,将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

我设法用回旋处解决了自己的问题。这不是最优雅的方法,但是可以。我非常感谢您提供的帮助,以使其更加优雅。

import numpy as np
from pathos.multiprocessing import ProcessingPool as Pool
from multiprocess import Manager


class ClothStoreNew(object):
    def __init__(self, num_customers):
        self.supply_arr = np.random.randint(5, size=(2, 2))
        self.num_customers = num_customers

    def make_purchase(self, arg):
        sold_dict = arg[0]
        i = arg[1]

        size = self.demand[i][1]
        color = self.demand[i][2]
        sold = sold_dict.get((size, color), 0)
        if self.supply_arr[size][color] > sold:
            sold_dict[(size, color)] = sold + 1

    def run(self):
        m = Manager()
        sold_dict = m.dict()
        pool = Pool(processes=100)
        self.demand = []
        for customer in xrange(self.num_customers):
            size = np.random.randint(1)
            color = np.random.randint(1)
            self.demand.append([customer, size, color])

        pool.map(self.make_purchase, ([sold_dict, i] for i in xrange(self.num_customers)))
        pool.close()
        pool.join()
        return dict(sold_dict)


if __name__ == "__main__":
    store = ClothStoreNew(20)
    sold_dict = store.run()
    print "Supply Arr: {}".format(store.supply_arr)
    print "Sold Dict: {}".format(sold_dict)

如您所见,我正在使用manager.dict()进行同步。我想使用manager.list(),但似乎不起作用。此外,使用Manager锁定每次更新的整个字典,理想的解决方案是一次锁定dict的每个单独键(或2D矩阵的每个单独单元格),以便进程在其他单元格不必等待。