我們將會看到一些在Python中使用線程的實例和如何避免線程之間的競爭。你應(yīng)當(dāng)將下邊的例子運行多次,以便可以注意到線程是不可預(yù)測的和線程每次運行出的不同結(jié)果。聲明:從這里開始忘掉你聽到過的關(guān)于GIL的東西,因為GIL不會影響到我想要展示的東西。
示例1
我們將要請求五個不同的url:
單線程
import timeimport 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 200http://www.amazon.com 200http://www.ebay.com 200http://www.alibaba.com 200http://www.reddit.com 200Elapsed time: 3.0814409256
解釋:
多線程
import urllib2import timefrom 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 200http://www.google.com 200http://www.amazon.com 200http://www.alibaba.com 200http://www.ebay.com 200Elapsed time: 0.689890861511
解釋:
關(guān)于線程:
實例2
我們將會用一個程序演示一下多線程間的資源競爭,并修復(fù)這個問題。
from threading import Thread #define a global variablesome_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é)果。
解釋:
為什么沒有達(dá)到50?
解決資源競爭
from threading import Lock, Threadlock = 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()
再次運行這個程序,達(dá)到了我們預(yù)期的結(jié)果。
解釋:
實例3
讓我們用一個例子來證明一個線程不能影響其他線程內(nèi)的變量(非全局變量)。
time.sleep()可以使一個線程掛起,強(qiáng)制線程切換發(fā)生。
from threading import Threadimport 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é)果。當(dāng)一個線程正在打印的時候,cpu切換到了另一個線程,所以產(chǎn)生了不正確的結(jié)果。我們需要確保print self.entries是個邏輯上的原子操作,以防打印時被其他線程打斷。
我們使用了Lock(),來看下邊的例子。
from threading import Thread, Lockimport 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)部的變量(非全局變量)。
新聞熱點
疑難解答
圖片精選