線程代碼:
import threading import time Lock = threading.Lock() def worker(i): Lock.acquire() print(threading.current_thread().name,"上鎖!") time.sleep(5) print("獲得的數據是:",i) Lock.release() print(threading.current_thread().name,"解鎖!") if __name__ == '__main__': start = time.time() Thread_List = [] for i in range(10): t = threading.Thread(target=worker,args=(i,)) Thread_List.append(t) for t in Thread_List: t.start() for t in Thread_List: t.join() end = time.time() print('完畢,用時:%s'%(end-start))
進程代碼:
import multiprocessing import time def worker(data,Semap): Semap.acquire() print(multiprocessing.current_process().name,"上鎖!") time.sleep(5) print('獲得的數據是:',data) Semap.release() print(multiprocessing.current_process().name,'解鎖!') if __name__ == '__main__': start = time.time() Process_List = [] Semap = multiprocessing.Semaphore(5) for i in range(10): t = multiprocessing.Process(target=worker, args=(i,Semap)) Process_List.append(t) for t in Process_List: t.start() for t in Process_List: t.join() end = time.time() print('完畢,用時:%s' % (end - start))
實驗: 兩個文件同時進行跑,看看哪個Python文件先跑完!
進程執行效果圖:
線程執行效果圖:
同樣是在函數執行的過程中進行了休眠5秒,然而執行之後的結果卻是讓人大跌眼鏡!
由於Python的GIL全局解釋器鎖的存在,線程的性能被大打則扣.因爲這個緣故,每次多線程在運行的時候,如果不希望數據是紊亂的,你就必須得加鎖!(上面的線程代碼上的Lock()換成RLock()也是一樣的.)一加鎖就跟沒開線程是一樣的.
所以,多線程在Python這裏就是雞肋.推薦使用多進程!
爬蟲的提速上面,多進程也是不錯的選擇.雖然爬蟲的網絡IO的,但是在多進程上的效率也不輸於多線程.