python多进程使用函数封装
importmultiprocessingasmpfrommultiprocessingimportProcessclassMyProcess(Process):"""自定义多进程,继承自原生Process,目的是获取多进程结果到queue"""def__init__(self,func,args,q):super(MyProcess,self).__init__()self.func=funcself.args=argsself.res=''self.q=q#self._daemonic=True#self._daemonic=Truedefrun(self):self.res=self.func(*self.args)self.q.put((self.func.__name__,self.res))defuse_multiprocessing(func_list):#os.system('exportPYTHONOPTIMIZE=1')#解决daemonicprocessesarenotallowedtohavechildren问题q=mp.Queue()#队列,将多进程结果存入这里,进程间共享,多进程必须使用multiprocessing的queueproc_list=[]res=[]forfuncinfunc_list:proc=MyProcess(func['func'],args=func['args'],q=q)proc.start()proc_list.append(proc)forpinproc_list:p.join()whilenotq.empty():r=q.get()res.append(r)returnres使用时候,将需要多进程执行的函数和函数的参数当作字段,组成个list传给use_multiprocessing方法即可
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。