對于Python中線程問題的簡單講解
我們將會看到一些在Python中使用線程的實例和如何避免線程之間的競爭。你應(yīng)當將下邊的例子運行多次,以便可以注意到線程是不可預(yù)測的和線程每次運行出的不同結(jié)果。聲明:從這里開始忘掉你聽到過的關(guān)于GIL的東西,因為GIL不會影響到我想要展示的東西。
示例1
我們將要請求五個不同的url:
單線程
import time import urllib2 def get_responses(): urls = [ 'http://www.google.com', 'http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com' ] start = time.time() for url in urls: print url resp = urllib2.urlopen(url) print resp.getcode() print "Elapsed time: %s" % (time.time()-start) get_responses()
輸出是:
http://www.google.com 200 http://www.amazon.com 200 http://www.ebay.com 200 http://www.alibaba.com 200 http://www.reddit.com 200 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 class GetUrlThread(Thread): def __init__(self, url): self.url = url super(GetUrlThread, self).__init__() def run(self): resp = urllib2.urlopen(self.url) print self.url, resp.getcode() def get_responses(): urls = [ 'http://www.google.com', 'http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com' ] start = time.time() threads = [] for url in urls: t = GetUrlThread(url) threads.append(t) t.start() for t in threads: t.join() print "Elapsed time: %s" % (time.time()-start) get_responses()
輸出:
http://www.reddit.com 200 http://www.google.com 200 http://www.amazon.com 200 http://www.alibaba.com 200 http://www.ebay.com 200 Elapsed time: 0.689890861511
解釋:
- 意識到了程序在執(zhí)行時間上的提升
- 我們寫了一個多線程程序來減少cpu的等待時間,當我們在等待一個線程內(nèi)的網(wǎng)絡(luò)請求返回時,這時cpu可以切換到其他線程去進行其他線程內(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 class IncrementThread(Thread): def run(self): #we want to read a global variable #and then increment it global some_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) def use_increment_thread(): threads = [] for i in range(50): t = IncrementThread() threads.append(t) t.start() for t in threads: 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,但是它卻沒有。
為什么沒有達到50?
- 在some_var是15的時候,線程t1讀取了some_var,這個時刻cpu將控制權(quán)給了另一個線程t2。
- t2線程讀到的some_var也是15
- t1和t2都把some_var加到16
- 當時我們期望的是t1 t2兩個線程使some_var + 2變成17
- 在這里就有了資源競爭。
- 相同的情況也可能發(fā)生在其它的線程間,所以出現(xiàn)了最后的結(jié)果小于50的情況。
解決資源競爭
from threading import Lock, Thread lock = Lock() some_var = 0 class IncrementThread(Thread): def run(self): #we want to read a global variable #and then increment it global some_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() def use_increment_thread(): threads = [] for i in range(50): t = IncrementThread() threads.append(t) t.start() for t in threads: 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ù)期的結(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 class CreateListThread(Thread): def run(self): self.entries = [] for i in range(10): time.sleep(1) self.entries.append(i) print self.entries def use_create_list_thread(): for i in range(3): t = CreateListThread() t.start() use_create_list_thread()
運行幾次后發(fā)現(xiàn)并沒有打印出爭取的結(jié)果。當一個線程正在打印的時候,cpu切換到了另一個線程,所以產(chǎn)生了不正確的結(jié)果。我們需要確保print self.entries是個邏輯上的原子操作,以防打印時被其他線程打斷。
我們使用了Lock(),來看下邊的例子。
from threading import Thread, Lock import time lock = Lock() class CreateListThread(Thread): def run(self): self.entries = [] for i in range(10): time.sleep(1) self.entries.append(i) lock.acquire() print self.entries lock.release() def use_create_list_thread(): for i in range(3): t = CreateListThread() t.start()use_create_list_thread()
這次我們看到了正確的結(jié)果。證明了一個線程不可以修改其他線程內(nèi)部的變量(非全局變量)。
相關(guān)文章
python matplotlib繪圖,修改坐標軸刻度為文字的實例
今天小編就為大家分享一篇python matplotlib繪圖,修改坐標軸刻度為文字的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05python去除字符串中的空格、特殊字符和指定字符的三種方法
本文主要介紹了python去除字符串中的空格、特殊字符和指定字符的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2023-02-02