Python中利用強大的threading模塊可以很容易的實現多線程開發,提高運行速度。這一般是對某個進行大量計算操作的的函數進行多線程處理,然后合並各線程的結果。獲取函數返回值的方法可以如下:
1). 利用multiprocessing.pool類
import time
import random
def test1(): # run without multi-thread
t = time.time()
list = []
for i in range(10000000):
list.append(random.choice([0,1,2,3,4,5])) # operation
print time.time()-t
return list
def test2(): # run with multi-thread
from multiprocessing.pool import Pool
def func(x):
return random.choice([0,1,2,3,4,5])
t = time.time()
pool = Pool(processes=4) #線程數
results = pool.map_async(func, range(10000000)) # 用法同map,與之相似的還有apply和apply_async
print time.time()-t
return results
r1 = test1()
r2 = test2()
運行結果為7.6s和4.2s。可以看到結果並非線性地減少4倍,這可能與運行結果需要同步有關(沒深入研究,猜的)。
2). 利用threading類
def func2(m, results, index):
for i in range(m):
result[index].append(random.choice([0,1,2,3,4,5]))
from threading import Thread
def test4():
threads = [None] * 4
results = [[] for i n range(4)]
for i in range(4):
threads[i] = Thread(target=func2, args=(2500000, results, i))
threads[i].start() # 開始線程
for i in range(4):
threads[i].join() # 等待線程結束后退出
return results
不過要注意的是只有在處理需要占用大量內存的數據的時候才考慮多線程,因為線程之間的同步問題很重要,因此設計函數的時候就需要注意,否則處理不好反而會產生很多問題。
參考
PS:threading模塊和multiprocessing模塊的文檔的說明十分詳細,准備好好研究下。
