您好,登錄后才能下訂單哦!
多線程概述
多線程使得程序內部可以分出多個線程來做多件事情,充分利用CPU空閑時間,提升處理效率。python提供了兩個模塊來實現多線程thread 和threading ,thread 有一些缺點,在threading 得到了彌補。并且在Python3中廢棄了thread模塊,保留了更強大的threading模塊。
使用場景
在python的原始解釋器CPython中存在著GIL(Global Interpreter Lock,全局解釋器鎖),因此在解釋執行python代碼時,會產生互斥鎖來限制線程對共享資源的訪問,直到解釋器遇到I/O操作或者操作次數達到一定數目時才會釋放GIL。所以,雖然CPython的線程庫直接封裝了系統的原生線程,但CPython整體作為一個進程,同一時間只會有一個獲得GIL的線程在跑,其他線程則處于等待狀態。這就造成了即使在多核CPU中,多線程也只是做著分時切換而已。
如果你的程序是CPU密集型,多個線程的代碼很有可能是線性執行的。所以這種情況下多線程是雞肋,效率可能還不如單線程因為有上下文切換開銷。但是如果你的代碼是IO密集型,涉及到網絡、磁盤IO的任務都是IO密集型任務,多線程可以明顯提高效率,例如多線程爬蟲,多線程文件處理等等
多線程爬蟲
多線程爬蟲的代碼實例
注: 以下代碼在python3下運行通過, python2版本差異較大,不能運行成功,如需幫助請下方留意。
# coding=utf-8 import threading, queue, time, urllib from urllib import request baseUrl = 'http://www.pythontab.com/html/pythonjichu/' urlQueue = queue.Queue() for i in range(2, 10): url = baseUrl + str(i) + '.html' urlQueue.put(url) #print(url) def fetchUrl(urlQueue): while True: try: #不阻塞的讀取隊列數據 url = urlQueue.get_nowait() i = urlQueue.qsize() except Exception as e: break print ('Current Thread Name %s, Url: %s ' % (threading.currentThread().name, url)) try: response = urllib.request.urlopen(url) responseCode = response.getcode() except Exception as e: continue if responseCode == 200: #抓取內容的數據處理可以放到這里 #為了突出效果, 設置延時 time.sleep(1) if __name__ == '__main__': startTime = time.time() threads = [] # 可以調節線程數, 進而控制抓取速度 threadNum = 4 for i in range(0, threadNum): t = threading.Thread(target=fetchUrl, args=(urlQueue,)) threads.append(t) for t in threads: t.start() for t in threads: #多線程多join的情況下,依次執行各線程的join方法, 這樣可以確保主線程最后退出, 且各個線程間沒有阻塞 t.join() endTime = time.time() print ('Done, Time cost: %s ' % (endTime - startTime))
運行結果:
1個線程時:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/8.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Done, Time cost: 8.182249069213867
2個線程時:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/8.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Done, Time cost: 4.0987958908081055
3個線程時:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-3, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-4, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-4, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Current Thread Name Thread-3, Url: http://www.pythontab.com/html/pythonjichu/8.html Done, Time cost: 2.287320137023926
通過調節線程數可以看到,執行時間會隨著線程數的增加而縮短,抓取效率成正比增加。
總結:
Python多線程在IO密集型任務,多線程可以明顯提高效率,CPU密集型任務不適合使用多線程處理。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。