python多進程中使用pool,python進程pool
Python 多進程中使用pool,pool中指定每次運行幾個進程,當其中一個進程結束完畢後,會加入新的進程
#!/usr/bin/env python#coding: utf-8import multiprocessingimport os,time,randomdef Lee(): print "Run task Lee-%s" %(os.getpid()) #os.getpid()擷取當前的進程的ID start=time.time() time.sleep(random.random()*10) #random.random()隨機產生0-1之間的小數 end=time.time() print 'Task Lee, runs %0.2f seconds.' %(end - start)def Marlon(): print "Run task Marlon-%s" %(os.getpid()) start=time.time() time.sleep(random.random()*40) end=time.time() print 'Task Marlon runs %0.2f seconds.' %(end - start)def Allen(): print "Run task Allen-%s" %(os.getpid()) start=time.time() time.sleep(random.random()*30) end=time.time() print 'Task Allen runs %0.2f seconds.' %(end - start)def Frank(): print "Run task Frank-%s" %(os.getpid()) start=time.time() time.sleep(random.random()*20) end=time.time() print 'Task Frank runs %0.2f seconds.' %(end - start) if __name__=='__main__': function_list= [Lee,Marlon,Allen,Frank] print "parent process %s" %(os.getpid()) pool=multiprocessing.Pool(2) for func in function_list: pool.apply_async(func) #Pool執行函數,apply執行函數,當有一個進程執行完畢後,會添加一個新的進程到pool中 print 'Waiting for all subprocesses done...' pool.close() pool.join() #調用join之前,一定要先調用close() 函數,否則會出錯, close()執行後不會有新的進程加入到pool,join函數等待素有子進程結束 print 'All subprocesses done.'