<轉摘>Python 並行任務技巧
支持Map並發的包文件有兩個:
Multiprocessing,還有少為人知的但卻功能強大的子文件 multiprocessing.dummy.
Dummy是一個多進程包的完整拷貝。唯一不同的是,多進程包使用進程,而dummy使用線程(自然也有Python本身的一些限制)。所以一個有的另一個也有。這樣在兩種模式間切換就十分簡單,並且在判斷框架調用時使用的是IO還是CPU模式非常有幫助.
導入相關包
1 from multiprocessing import Pool
或者 2 from multiprocessing.dummy import Pool as ThreadPool
初始化
1 pool = ThreadPool()
1 import urllib2 2 from multiprocessing.dummy import Pool as ThreadPool 3 4 urls = [ 5 'http://www.python.org', 6 'http://www.python.org/about/', 7 'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html', 8 'http://www.python.org/doc/', 9 'http://www.python.org/download/', 10 'http://www.python.org/getit/', 11 'http://www.python.org/community/', 12 'https://wiki.python.org/moin/', 13 'http://planet.python.org/', 14 'https://wiki.python.org/moin/LocalUserGroups', 15 'http://www.python.org/psf/', 16 'http://docs.python.org/devguide/', 17 'http://www.python.org/community/awards/' 18 # etc.. 19 ] 20 21 # Make the Pool of workers 22 pool = ThreadPool(4) 23 # Open the urls in their own threads 24 # and return the results 25 results = pool.map(urllib2.urlopen, urls) 26 #close the pool and wait for the work to finish 27 pool.close() 28 pool.join()
pool對象需要一些參數。它可以限定線程池中worker的數量。如果不填,它將采用系統的內核數作為初值.
如果你進行的是計算密集型多進程任務,內核越多意味着速度越快(當然這是有前提的)。但如果是涉及到網絡計算方面,影響的因素就千差萬別。所以最好還是能給出合適的線程池大小數
如果運行的線程很多,頻繁的切換線程會十分影響工作效率。所以最好還是能通過調試找出任務調度的時間平衡點
