歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python多進程中使用pool

Python多進程中使用pool

日期:2017/3/1 9:33:00   编辑:Linux編程

Python 多進程中使用pool,pool中指定每次運行幾個進程,當其中一個進程結束完畢後,會加入新的進程

#!/usr/bin/env python
#coding: utf-8
import multiprocessing
import os,time,random

def 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.'

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved