介绍
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)