加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 多处理 – 共享阵列

发布时间:2020-12-20 13:13:43 所属栏目:Python 来源:网络整理
导读:所以我正在尝试在 python中实现多处理,我希望有一个4-5进程池并行运行一个方法.这样做的目的是运行总共1000个Monte模拟(每个进程250-200个模拟)而不是运行1000.我希望每个进程在完成处理后立即通过获取锁定来写入公共共享数组一次模拟的结果,写入结果并释放
所以我正在尝试在 python中实现多处理,我希望有一个4-5进程池并行运行一个方法.这样做的目的是运行总共1000个Monte模拟(每个进程250-200个模拟)而不是运行1000.我希望每个进程在完成处理后立即通过获取锁定来写入公共共享数组一次模拟的结果,写入结果并释放锁定.所以它应该是一个三步过程:

>获得锁定
>写出结果
>释放等待写入阵列的其他进程的锁定.

每次我将数组传递给进程时,每个进程都会创建一个我不想要的数组副本,因为我想要一个公共数组.任何人都可以通过提供示例代码来帮助我吗?

解决方法

由于您只是将状态从子进程返回到父进程,因此使用共享数组和显式锁是过度的.您可以使用Pool.map或Pool.starmap来完全满足您的需求.例如:

from multiprocessing import Pool

class Adder:
    """I'm using this class in place of a monte carlo simulator"""

    def add(self,a,b):
        return a + b

def setup(x,y,z):
    """Sets up the worker processes of the pool. 
    Here,x,and z would be your global settings. They are only included
    as an example of how to pass args to setup. In this program they would
    be "some arg","another" and 2
    """
    global adder
    adder = Adder()

def job(a,b):
    """wrapper function to start the job in the child process"""
    return adder.add(a,b)

if __name__ == "__main__":   
    args = list(zip(range(10),range(10,20)))
    # args == [(0,10),(1,11),...,(8,18),(9,19)]

    with Pool(initializer=setup,initargs=["some arg","another",2]) as pool:
        # runs jobs in parallel and returns when all are complete
        results = pool.starmap(job,args)

    print(results) # prints [10,12,26,28]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读