Python 多进程模块 multiprocessing - 简单使用

示例代码

问题:随机生成 1 0 4 10^4 104 个在 [ 0 , 100 ) [0, 100) [0,100)之间的整数,获取每个数的平均值,并把所有结果写入文件中。

import numpy as np
import multiprocessing


def power(numbers, list_obj):
    """
    :param numbers: 输入的单个chunk的随机数字
    :param list_obj: 用于保存最终结果的列表
    :return:
    """
    res = []
    for number in numbers:
        res.append(number**2)
    list_obj.append(res)


if __name__ == '__main__':
    # 指定进程数量
    n_cpu = 20
    # 创建一个服务进程,用于多进程间的通信(保存每个进程的结果),这里创建list对象来保存处理的结果。
    mgr = multiprocessing.Manager()
    list_obj = mgr.list()
    # 随机生成数据并将数据分为 n_cpu 份
    numbers = np.random.randint(low=0, high=100, size=int(10e4))
    chunks = [list(i) for i in np.array_split(numbers, n_cpu)]
    # 创建进程实例,并绑定其函数以及需要传入的数据
    jobs = []
    for i in range(n_cpu):
        p = multiprocessing.Process(target=power,
                                    args=(chunks[i], list_obj))
        jobs.append(p)
        # 开始
        p.start()

    # 等待所有进程完成
    for p in jobs:
        p.join()

    # 整合处理后的数据
    res = []
    for i in list_obj:
        res += i
    res = np.array(res).astype(int)

    # 保存处理后的结果
    np.savetxt('res.txt', res, fmt='%d')

1.相关知识

服务进程

由 Manager() 返回的管理器对象控制一个服务器进程,该进程保存Python对象并允许其他进程使用代理操作它们。
Manager() 返回的管理器支持类型: list 、 dict 、 Namespace 、 Lock 、 RLock 、 Semaphore 、 BoundedSemaphore 、 Condition 、 Event 、 Barrier 、 Queue 、 Value 和 Array。

2.参考

numpy.random.randint https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.htm
numpy.array_split
https://numpy.org/doc/stable/reference/generated/numpy.array_split.html
numpy.savetxt
https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html
multiprocessing
https://docs.python.org/3/library/multiprocessing.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值