深入理解 Python 中的多線程 新手必看
示例1
我們將要請求五個不同的url:
單線程
import time import urllib2 defget_responses(): urls=[ ‘http://www.baidu.com', ‘http://www.amazon.com', ‘http://www.ebay.com', ‘http://www.alibaba.com', ‘http://www.dbjr.com.cn' ] start=time.time() forurlinurls: printurl resp=urllib2.urlopen(url) printresp.getcode() print”Elapsed time: %s”%(time.time()-start) get_responses()
輸出是:
http://www.baidu.com200
http://www.amazon.com200
http://www.ebay.com200
http://www.alibaba.com200
http://www.dbjr.com.cn200
Elapsed time:3.0814409256
解釋:
url順序的被請求
除非cpu從一個url獲得了回應(yīng),否則不會去請求下一個url
網(wǎng)絡(luò)請求會花費較長的時間,所以cpu在等待網(wǎng)絡(luò)請求的返回時間內(nèi)一直處于閑置狀態(tài)。
多線程
import urllib2 import time from threading import Thread classGetUrlThread(Thread): def__init__(self, url): self.url=url super(GetUrlThread,self).__init__() defrun(self): resp=urllib2.urlopen(self.url) printself.url, resp.getcode() defget_responses(): urls=[ ‘http://www.baidu.com', ‘http://www.amazon.com', ‘http://www.ebay.com', ‘http://www.alibaba.com', ‘http://www.dbjr.com.cn' ] start=time.time() threads=[] forurlinurls: t=GetUrlThread(url) threads.append(t) t.start() fortinthreads: t.join() print”Elapsed time: %s”%(time.time()-start) get_responses()
輸出:
http://www.dbjr.com.cn200
http://www.baidu.com200
http://www.amazon.com200
http://www.alibaba.com200
http://www.ebay.com200
Elapsed time:0.689890861511
解釋:
意識到了程序在執(zhí)行時間上的提升
我們寫了一個多線程程序來減少cpu的等待時間,當(dāng)我們在等待一個線程內(nèi)的網(wǎng)絡(luò)請求返回時,這時cpu可以切換到其他線程去進(jìn)行其他線程內(nèi)的網(wǎng)絡(luò)請求。
我們期望一個線程處理一個url,所以實例化線程類的時候我們傳了一個url。
線程運行意味著執(zhí)行類里的run()方法。
無論如何我們想每個線程必須執(zhí)行run()。
為每個url創(chuàng)建一個線程并且調(diào)用start()方法,這告訴了cpu可以執(zhí)行線程中的run()方法了。
我們希望所有的線程執(zhí)行完畢的時候再計算花費的時間,所以調(diào)用了join()方法。
join()可以通知主線程等待這個線程結(jié)束后,才可以執(zhí)行下一條指令。
每個線程我們都調(diào)用了join()方法,所以我們是在所有線程執(zhí)行完畢后計算的運行時間。
關(guān)于線程:
cpu可能不會在調(diào)用start()后馬上執(zhí)行run()方法。
你不能確定run()在不同線程建間的執(zhí)行順序。
對于單獨的一個線程,可以保證run()方法里的語句是按照順序執(zhí)行的。
這就是因為線程內(nèi)的url會首先被請求,然后打印出返回的結(jié)果。
實例2
我們將會用一個程序演示一下多線程間的資源競爭,并修復(fù)這個問題。
from threading import Thread #define a global variable some_var=0 classIncrementThread(Thread): defrun(self): #we want to read a global variable #and then increment it globalsome_var read_value=some_var print”some_var in %s is %d”%(self.name, read_value) some_var=read_value+1 print”some_var in %s after increment is %d”%(self.name, some_var) defuse_increment_thread(): threads=[] foriinrange(50): t=IncrementThread() threads.append(t) t.start() fortinthreads: t.join() print”After 50 modifications, some_var should have become 50″ print”After 50 modifications, some_var is %d”%(some_var,) use_increment_thread()
多次運行這個程序,你會看到多種不同的結(jié)果。
解釋:
有一個全局變量,所有的線程都想修改它。
所有的線程應(yīng)該在這個全局變量上加 1 。
有50個線程,最后這個數(shù)值應(yīng)該變成50,但是它卻沒有。
為什么沒有達(dá)到50?
在some_var是15的時候,線程t1讀取了some_var,這個時刻cpu將控制權(quán)給了另一個線程t2。
t2線程讀到的some_var也是15
t1和t2都把some_var加到16
當(dāng)時我們期望的是t1 t2兩個線程使some_var + 2變成17
在這里就有了資源競爭。
相同的情況也可能發(fā)生在其它的線程間,所以出現(xiàn)了最后的結(jié)果小于50的情況。
解決資源競爭
from threading import Lock, Thread lock=Lock() some_var=0 classIncrementThread(Thread): defrun(self): #we want to read a global variable #and then increment it globalsome_var lock.acquire() read_value=some_var print”some_var in %s is %d”%(self.name, read_value) some_var=read_value+1 print”some_var in %s after increment is %d”%(self.name, some_var) lock.release() defuse_increment_thread(): threads=[] foriinrange(50): t=IncrementThread() threads.append(t) t.start() fortinthreads: t.join() print”After 50 modifications, some_var should have become 50″ print”After 50 modifications, some_var is %d”%(some_var,) use_increment_thread()
再次運行這個程序,達(dá)到了我們預(yù)期的結(jié)果。
解釋:
Lock 用來防止競爭條件
如果在執(zhí)行一些操作之前,線程t1獲得了鎖。其他的線程在t1釋放Lock之前,不會執(zhí)行相同的操作
我們想要確定的是一旦線程t1已經(jīng)讀取了some_var,直到t1完成了修改some_var,其他的線程才可以讀取some_var
這樣讀取和修改some_var成了邏輯上的原子操作。
實例3
讓我們用一個例子來證明一個線程不能影響其他線程內(nèi)的變量(非全局變量)。
time.sleep()可以使一個線程掛起,強制線程切換發(fā)生。
from threading import Thread import time classCreateListThread(Thread): defrun(self): self.entries=[] foriinrange(10): time.sleep(1) self.entries.append(i) printself.entries defuse_create_list_thread(): foriinrange(3): t=CreateListThread() t.start() use_create_list_thread()
運行幾次后發(fā)現(xiàn)并沒有打印出爭取的結(jié)果。當(dāng)一個線程正在打印的時候,cpu切換到了另一個線程,所以產(chǎn)生了不正確的結(jié)果。我們需要確保print self.entries是個邏輯上的原子操作,以防打印時被其他線程打斷。
我們使用了Lock(),來看下邊的例子。
from threading import Thread, Lock import time lock=Lock() classCreateListThread(Thread): defrun(self): self.entries=[] foriinrange(10): time.sleep(1) self.entries.append(i) lock.acquire() printself.entries lock.release() defuse_create_list_thread(): foriinrange(3): t=CreateListThread() t.start() use_create_list_thread()
這次我們看到了正確的結(jié)果。證明了一個線程不可以修改其他線程內(nèi)部的變量(非全局變量)。
相關(guān)文章
詳解python 利用echarts畫地圖(熱力圖)(世界地圖,省市地圖,區(qū)縣地圖)
這篇文章主要介紹了詳解python 利用echarts畫地圖(熱力圖)(世界地圖,省市地圖,區(qū)縣地圖),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Python實現(xiàn)Appium端口檢測與釋放的實現(xiàn)
這篇文章主要介紹了Python實現(xiàn)Appium端口檢測與釋放的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12基于Python實現(xiàn)RLE格式分割標(biāo)注文件的格式轉(zhuǎn)換
本文將以Airbus Ship Detection Challenge為例,為大家詳細(xì)講解Python實現(xiàn)RLE格式分割標(biāo)注文件格式轉(zhuǎn)換的方法,感興趣的可以了解一下2022-08-08python-opencv-cv2.threshold()二值化函數(shù)的使用
這篇文章主要介紹了python-opencv-cv2.threshold()二值化函數(shù)的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11Python利用PyMuPDF實現(xiàn)PDF文件處理
PyMuPDF是MuPDF的Python綁定-“輕量級PDF和XPS查看器”。本文將利用PyMuPDF實現(xiàn)PDF的一些基本操作,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-05-05