python是支持多線程的,主要是通過thread和threading這兩個(gè)模塊來實(shí)現(xiàn)的。thread模塊是比較底層的模塊,threading模塊是對(duì)thread做了一些包裝的,可以更加方便的使用。
雖然python的多線程受GIL限制,并不是真正的多線程,但是對(duì)于I/O密集型計(jì)算還是能明顯提高效率,比如說爬蟲。
下面用一個(gè)實(shí)例來驗(yàn)證多線程的效率。代碼只涉及頁(yè)面獲取,并沒有解析出來。
# -*-coding:utf-8 -*- import urllib2, time import threading class MyThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) self.args = args self.func = func def run(self): apply(self.func, self.args) def open_url(url): request = urllib2.Request(url) html = urllib2.urlopen(request).read() print len(html) return html
if __name__ == '__main__': # 構(gòu)造url列表 urlList = [] for p in range(1, 10): urlList.append('http://s.wanfangdata.com.cn/Paper.aspx?q=%E5%8C%BB%E5%AD%A6&p=' + str(p))
# 一般方式 n_start = time.time() for each in urlList: open_url(each) n_end = time.time() print 'the normal way take %s s' % (n_end-n_start)
# 多線程 t_start = time.time() threadList = [MyThread(open_url, (url,)) for url in urlList] for t in threadList: t.setDaemon(True) t.start() for i in threadList: i.join() t_end = time.time() print 'the thread way take %s s' % (t_end-t_start)
分別用兩種方式獲取10個(gè)訪問速度比較慢的網(wǎng)頁(yè),一般方式耗時(shí)50s,多線程耗時(shí)10s。
多線程代碼解讀:
# 創(chuàng)建線程類,繼承Thread類 class MyThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) # 調(diào)用父類的構(gòu)造函數(shù) self.args = args self.func = func def run(self): # 線程活動(dòng)方法 apply(self.func, self.args)
threadList = [MyThread(open_url, (url,)) for url in urlList] # 調(diào)用線程類創(chuàng)建新線程,返回線程列表 for t in threadList: t.setDaemon(True) # 設(shè)置守護(hù)線程,父線程會(huì)等待子線程執(zhí)行完后再退出 t.start() # 線程開啟 for i in threadList: i.join() # 等待線程終止,等子線程執(zhí)行完后再執(zhí)行父線程
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
