如何在python多处理中的进程之间共享类的同步列表

时间:2019-05-11 16:00:12

标签: python python-3.x multiprocessing python-multiprocessing

使用多重处理时如何共享状态并同步类列表。

下面有一个简单的例子,其中我在增加3个人钱包的数量。这三个人的起薪金额不同。我重复了10次,每次都给他们额外的10次。

import concurrent.futures
import multiprocessing as mp
from multiprocessing import Manager
from ctypes import py_object

class Wallet():

    def __init__(self, name, amount):
        self.name = name
        self.amount = amount

def give(num):

    for w in _WALLETLIST:

        # with l.get_lock():
        w.amount += num
        print("Name: ", w.name, " Amount: ", w.amount)


def init_globals(walletList):
    global _WALLETLIST
    _WALLETLIST = walletList

def main():

    wallet1 = Wallet("John", 100)
    wallet2 = Wallet("Alice", 200)
    wallet3 = Wallet("Bob", 300)
    amount_per_week = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

    walletList = [wallet1, wallet2, wallet3]

    mp_walletList = mp.Array(py_object, walletList)

    with concurrent.futures.ProcessPoolExecutor(initializer=init_globals, initargs=(mp_walletList,)) as executor:
        for _ in executor.map(give, amount_per_week):
            pass
    print()


if __name__ == "__main__":
    main()

最后我希望约翰有200个,爱丽丝有300个,鲍勃有400个。

我尝试了multiprocessing.Array,但是我没有找到传递类的方法来共享和同步它。

0 个答案:

没有答案