深入理解 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://m.fzitv.net'
]
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://m.fzitv.net200
Elapsed time:3.0814409256
解釋:
url順序的被請求
除非cpu從一個url獲得了回應(yīng),否則不會去請求下一個url
網(wǎng)絡(luò)請求會花費(fèi)較長的時間,所以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://m.fzitv.net'
]
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://m.fzitv.net200
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,所以實(shí)例化線程類的時候我們傳了一個url。
線程運(yùn)行意味著執(zhí)行類里的run()方法。
無論如何我們想每個線程必須執(zhí)行run()。
為每個url創(chuàng)建一個線程并且調(diào)用start()方法,這告訴了cpu可以執(zhí)行線程中的run()方法了。
我們希望所有的線程執(zhí)行完畢的時候再計(jì)算花費(fèi)的時間,所以調(diào)用了join()方法。
join()可以通知主線程等待這個線程結(jié)束后,才可以執(zhí)行下一條指令。
每個線程我們都調(diào)用了join()方法,所以我們是在所有線程執(zhí)行完畢后計(jì)算的運(yùn)行時間。
關(guān)于線程:
cpu可能不會在調(diào)用start()后馬上執(zhí)行run()方法。
你不能確定run()在不同線程建間的執(zhí)行順序。
對于單獨(dú)的一個線程,可以保證run()方法里的語句是按照順序執(zhí)行的。
這就是因?yàn)榫€程內(nèi)的url會首先被請求,然后打印出返回的結(jié)果。
實(shí)例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()
多次運(yùn)行這個程序,你會看到多種不同的結(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()
再次運(yùn)行這個程序,達(dá)到了我們預(yù)期的結(jié)果。
解釋:
Lock 用來防止競爭條件
如果在執(zhí)行一些操作之前,線程t1獲得了鎖。其他的線程在t1釋放Lock之前,不會執(zhí)行相同的操作
我們想要確定的是一旦線程t1已經(jīng)讀取了some_var,直到t1完成了修改some_var,其他的線程才可以讀取some_var
這樣讀取和修改some_var成了邏輯上的原子操作。
實(shí)例3
讓我們用一個例子來證明一個線程不能影響其他線程內(nèi)的變量(非全局變量)。
time.sleep()可以使一個線程掛起,強(qiáng)制線程切換發(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()
運(yùn)行幾次后發(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)文章
PyCharm設(shè)置SSH遠(yuǎn)程調(diào)試的方法
這篇文章主要介紹了PyCharm設(shè)置SSH遠(yuǎn)程調(diào)試的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
pandas實(shí)現(xiàn)數(shù)據(jù)讀取&清洗&分析的項(xiàng)目實(shí)踐
近期因工作需要,需對幾十萬條商品和訂單數(shù)據(jù)進(jìn)行初步的數(shù)據(jù)分析,本文主要pandas實(shí)現(xiàn)數(shù)據(jù)讀取&清洗&分析的項(xiàng)目實(shí)踐,具有一定的參考價值,感興趣的可以了解一下2022-05-05
tensorflow獲取預(yù)訓(xùn)練模型某層參數(shù)并賦值到當(dāng)前網(wǎng)絡(luò)指定層方式
今天小編就為大家分享一篇tensorflow獲取預(yù)訓(xùn)練模型某層參數(shù)并賦值到當(dāng)前網(wǎng)絡(luò)指定層方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
arcgis使用Python腳本進(jìn)行批量截圖功能實(shí)現(xiàn)
最近公司數(shù)據(jù)部那邊有個需求,需要結(jié)合矢量數(shù)據(jù)和影像數(shù)據(jù),進(jìn)行批量截圖,并且截圖中只能有一個圖斑,還要添加上相應(yīng)的水印,這篇文章主要介紹了arcgis使用Python腳本進(jìn)行批量截圖,需要的朋友可以參考下2023-01-01
Python實(shí)現(xiàn)ATM系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)ATM系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-02-02
Python-torch?之torch.clamp()?函數(shù)解析
torch.clamp()函數(shù)用于對輸入張量進(jìn)行截?cái)嗖僮鳎瑢埩恐械拿總€元素限制在指定的范圍內(nèi),這篇文章主要介紹了Python torch之torch.clamp()函數(shù),需要的朋友可以參考下2023-05-05

