Python多線程原理與用法實例剖析
本文實例講述了Python多線程原理與用法。分享給大家供大家參考,具體如下:
先來看個栗子:
下面來看一下I/O秘籍型的線程,舉個栗子——爬蟲,下面是爬下來的圖片用4個線程去寫文件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import urllib
import threading
import Queue
import timeit
def getHtml(url):
html_page = urllib.urlopen(url).read()
return html_page
# 提取網(wǎng)頁中圖片的URL
def getUrl(html):
pattern = r'src="(http://img.*?)"' # 正則表達式
imgre = re.compile(pattern)
imglist = re.findall(imgre, html) # re.findall(pattern,string) 在string中尋找所有匹配成功的字符串,以列表形式返回值
return imglist
class getImg(threading.Thread):
def __init__(self, queue, thread_name=0): # 線程公用一個隊列
threading.Thread.__init__(self)
self.queue = queue
self.thread_name = thread_name
self.start() # 啟動線程
# 使用隊列實現(xiàn)進程間通信
def run(self):
global count
while (True):
imgurl = self.queue.get() # 調(diào)用隊列對象的get()方法從隊頭刪除并返回一個項目
urllib.urlretrieve(imgurl, 'E:\mnt\girls\%s.jpg' % count)
count += 1
if self.queue.empty():
break
self.queue.task_done() # 當使用者線程調(diào)用 task_done() 以表示檢索了該項目、并完成了所有的工作時,那么未完成的任務的總數(shù)就會減少。
imglist = []
def main():
global imglist
url = "http://huaban.com/favorite/beauty/" # 要爬的網(wǎng)頁地址
html = getHtml(url)
imglist = getUrl(html)
def main_1():
global count
threads = []
count = 0
queue = Queue.Queue()
# 將所有任務加入隊列
for img in imglist:
queue.put(img)
# 多線程爬去圖片
for i in range(4):
thread = getImg(queue, i)
threads.append(thread)
# 阻塞線程,直到線程執(zhí)行完成
for thread in threads:
thread.join()
if __name__ == '__main__':
main()
t = timeit.Timer(main_1)
print t.timeit(1)
4個線程的執(zhí)行耗時為:0.421320716723秒
修改一下main_1換成單線程的:
def main_1():
global count
threads = []
count = 0
queue = Queue.Queue()
# 將所有任務加入隊列
for img in imglist:
queue.put(img)
# 多線程爬去圖片
for i in range(1):
thread = getImg(queue, i)
threads.append(thread)
# 阻塞線程,直到線程執(zhí)行完成
for thread in threads:
thread.join()
單線程的執(zhí)行耗時為:1.35626623274秒

再來看一個:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import timeit
def countdown(n):
while n > 0:
n -= 1
def task1():
COUNT = 100000000
thread1 = threading.Thread(target=countdown, args=(COUNT,))
thread1.start()
thread1.join()
def task2():
COUNT = 100000000
thread1 = threading.Thread(target=countdown, args=(COUNT // 2,))
thread2 = threading.Thread(target=countdown, args=(COUNT // 2,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
if __name__ == '__main__':
t1 = timeit.Timer(task1)
print "countdown in one thread ", t1.timeit(1)
t2 = timeit.Timer(task2)
print "countdown in two thread ", t2.timeit(1)
task1是單線程,task2是雙線程,在我的4核的機器上的執(zhí)行結(jié)果:
countdown in one thread 3.59939150155
countdown in two thread 9.87704289712
天吶,雙線程比單線程計算慢了2倍多,這是為什么呢,因為countdown是CPU密集型任務(計算嘛)

I/O密集型任務:線程做I/O處理的時候會釋放GIL,其他線程獲得GIL,當該線程再做I/O操作時,又會釋放GIL,如此往復;
CPU密集型任務:在多核多線程比單核多線程更差,原因是單核多線程,每次釋放GIL,喚醒的哪個線程都能獲取到GIL鎖,所以能夠無縫執(zhí)行(單核多線程的本質(zhì)就是順序執(zhí)行),但多核,CPU0釋放GIL后,其他CPU上的線程都會進行競爭,但GIL可能會馬上又被CPU0(CPU0上可能不止一個線程)拿到,導致其他幾個CPU上被喚醒后的線程會醒著等待到切換時間后又進入待調(diào)度狀態(tài),這樣會造成線程顛簸(thrashing),導致效率更低。
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
使用Python中的cookielib模擬登錄網(wǎng)站
這篇文章主要介紹了使用Python中的cookielib模擬登錄網(wǎng)站,用作生成cookie然后登錄,需要的朋友可以參考下2015-04-04
pandas滑動窗口學習筆記(shift, diff, pct_change)
pandas中有3類窗口,分別是滑動窗口rolling?、擴張窗口expanding以及指數(shù)加權(quán)窗口ewm,下面就來詳細的介紹一下這三種的用法,感興趣的可以了解一下2024-03-03
使用python怎樣產(chǎn)生10個不同的隨機數(shù)
這篇文章主要介紹了使用python實現(xiàn)產(chǎn)生10個不同的隨機數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

