Python 多进程程序框架

介绍

python多进程框架用于编写多进程程序

注意

  • 多进程程序报错不会输出, 先用单进程调试完成后才运行
  • 多进程的子进程函数请用单独的类封装, 否者子程序函数不会运行
import os
from multiprocessing import Pool,cpu_count
import time

class MainProgress:
    def __init__(self):
        self.fileCount = 1000000
        '''初始化多进程池'''
        self.p = Pool()
    def Run(self,multiProcessFlag=True,num_workers=cpu_count()):

        print("=========================================")
        print(" MultiProcess ")
        print("=========================================")

        '''自动batch:通过给多进程分割总任务每个进程处理一个batch'''
        batch = int(self.fileCount / num_workers)

        start=0
        end =batch
        sub=SubProcess()
        stopFlag=False
        while True:

            '''为每个子list启动多进程'''
            if multiProcessFlag==True:
                self.p.apply_async(sub.Run, args = (start,end,))
            else:
                # 单进程模式测试功能函数是否报错(因为多进程报错不会有提示)
                sub.Run(start,end)

            start += batch
            end += batch
            if stopFlag==True:
                break
            if end>=self.fileCount and stopFlag != True:
                end=self.fileCount
                '''保证这个if只会在batch不足的时候运行一次然后跳出循环'''
                stopFlag=True

        #等待多进程执行完毕后释放
        self.p.close()
        self.p.join()

class SubProcess:
    # 子进程初始化,可以初始化类似于目录之类的
    def __init__(self):
        pass
    #子进程要做的任务
    def Run(self,start,end):

        subCount = start
        while subCount!=end:

            print(" Pid = " + str(os.getpid())+" subCount: "+str(subCount))
            subCount += 1

if __name__ =="__main__":
    t1=time.time()
    print("start-------------------------------------")
    # splitRatio = sys.argv[1]
    #mode = sys.argv[1]  # 第二个参数输入修改的文件目录

    mProgress = MainProgress()
    mProgress.Run(multiProcessFlag=True)

    print("end--------------------------------------")
    t2=time.time()
    print("Used time: ",t2-t1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值