什么叫Python3 多線程掺喻?如何學(xué)多線程?教你一招

Python3 線程中常用的兩個模塊為:

_thread

threading(推薦使用)

thread 模塊已被廢棄储矩。用戶可以使用 threading 模塊代替感耙。所以,在 Python3 中不能再使用"thread" 模塊持隧。為了兼容性即硼,Python3 將 thread 重命名為 "_thread"。

開始學(xué)習(xí) Python 線程

Python 中使用線程有兩種方式:函數(shù)或者用類來包裝線程對象屡拨。

函數(shù)式:調(diào)用 _thread 模塊中的 start_new_thread() 函數(shù)來產(chǎn)生新線程只酥。語法如下:

_thread.start_new_thread ( function, args[, kwargs] )

參數(shù)說明:

function - 線程函數(shù)。

args - 傳遞給線程函數(shù)的參數(shù),他必須是個 tuple 類型呀狼。

kwargs - 可選參數(shù)层皱。

實例:

#!/usr/bin/python3

import _thread

import time

# 為線程定義一個函數(shù)

def print_time( threadName, delay):

? count = 0

? while count < 5:

? ? ? time.sleep(delay)

? ? ? count += 1

? ? ? print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 創(chuàng)建兩個線程

try:

? _thread.start_new_thread( print_time, ("Thread-1", 2, ) )

? _thread.start_new_thread( print_time, ("Thread-2", 4, ) )

except:

? print ("Error: 無法啟動線程")

while 1:

? pass

執(zhí)行以上程序輸出結(jié)果如下:

Thread-1: Wed Apr? 6 11:36:31 2016

Thread-1: Wed Apr? 6 11:36:33 2016

Thread-2: Wed Apr? 6 11:36:33 2016

Thread-1: Wed Apr? 6 11:36:35 2016

Thread-1: Wed Apr? 6 11:36:37 2016

Thread-2: Wed Apr? 6 11:36:37 2016

Thread-1: Wed Apr? 6 11:36:39 2016

Thread-2: Wed Apr? 6 11:36:41 2016

Thread-2: Wed Apr? 6 11:36:45 2016

Thread-2: Wed Apr? 6 11:36:49 2016

執(zhí)行以上程后可以按下 ctrl-c to 退出。

線程模塊

Python3 通過兩個標準庫 _thread 和 threading 提供對線程的支持赠潦。

_thread 提供了低級別的叫胖、原始的線程以及一個簡單的鎖,它相比于 threading 模塊的功能還是比較有限的她奥。

threading 模塊除了包含 _thread 模塊中的所有方法外瓮增,還提供的其他方法:

threading.currentThread(): 返回當前的線程變量。

threading.enumerate(): 返回一個包含正在運行的線程的list哩俭。正在運行指線程啟動后绷跑、結(jié)束前,不包括啟動前和終止后的線程凡资。

threading.activeCount(): 返回正在運行的線程數(shù)量砸捏,與 len(threading.enumerate()) 有相同的結(jié)果。

使用 threading 模塊創(chuàng)建線程

我們可以通過直接從 threading.Thread 繼承創(chuàng)建一個新的子類隙赁,并實例化后調(diào)用 start() 方法啟動新線程垦藏,即它調(diào)用了線程的 run() 方法:

#!/usr/bin/python3

import threading

import time

exitFlag = 0

class myThread (threading.Thread):

? ? def __init__(self, threadID, name, counter):

? ? ? ? threading.Thread.__init__(self)

? ? ? ? self.threadID = threadID

? ? ? ? self.name = name

? ? ? ? self.counter = counter

? ? def run(self):

? ? ? ? print ("開始線程:" + self.name)

? ? ? ? print_time(self.name, self.counter, 5)

? ? ? ? print ("退出線程:" + self.name)

def print_time(threadName, delay, counter):

? ? while counter:

? ? ? ? if exitFlag:

? ? ? ? ? ? threadName.exit()

? ? ? ? time.sleep(delay)

? ? ? ? print ("%s: %s" % (threadName, time.ctime(time.time())))

? ? ? ? counter -= 1

# 創(chuàng)建新線程

thread1 = myThread(1, "Thread-1", 1)

thread2 = myThread(2, "Thread-2", 2)

# 開啟新線程

thread1.start()

thread2.start()

thread1.join()

thread2.join()

print ("退出主線程")

以上程序執(zhí)行結(jié)果如下;

開始線程:Thread-1

開始線程:Thread-2

Thread-1: Wed Apr? 6 11:46:46 2016

Thread-1: Wed Apr? 6 11:46:47 2016

Thread-2: Wed Apr? 6 11:46:47 2016

Thread-1: Wed Apr? 6 11:46:48 2016

Thread-1: Wed Apr? 6 11:46:49 2016

Thread-2: Wed Apr? 6 11:46:49 2016

Thread-1: Wed Apr? 6 11:46:50 2016

退出線程:Thread-1

Thread-2: Wed Apr? 6 11:46:51 2016

Thread-2: Wed Apr? 6 11:46:53 2016

Thread-2: Wed Apr? 6 11:46:55 2016

退出線程:Thread-2

退出主線程

線程同步

使用 Thread 對象的 Lock 和 Rlock 可以實現(xiàn)簡單的線程同步伞访,這兩個對象都有 acquire 方法和 release 方法掂骏,對于那些需要每次只允許一個線程操作的數(shù)據(jù),可以將其操作放到 acquire 和 release 方法之間厚掷。如下:

多線程的優(yōu)勢在于可以同時運行多個任務(wù)(至少感覺起來是這樣)弟灼。但是當線程需要共享數(shù)據(jù)時级解,可能存在數(shù)據(jù)不同步的問題。

考慮這樣一種情況:一個列表里所有元素都是 0田绑,線程"set"從后向前把所有元素改成 1勤哗,而線程"print"負責(zé)從前往后讀取列表并打印。

那么掩驱,可能線程"set"開始改的時候芒划,線程"print"便來打印列表了,輸出就成了一半 0 一半 1昙篙,這就是數(shù)據(jù)的不同步腊状。為了避免這種情況,引入了鎖的概念苔可。

鎖有兩種狀態(tài)——鎖定和未鎖定缴挖。每當一個線程比如"set"要訪問共享數(shù)據(jù)時,必須先獲得鎖定焚辅;如果已經(jīng)有別的線程比如"print"獲得鎖定了映屋,那么就讓線程"set"暫停,也就是同步阻塞同蜻;等到線程"print"訪問完畢棚点,釋放鎖以后,再讓線程"set"繼續(xù)湾蔓。

經(jīng)過這樣的處理瘫析,打印列表時要么全部輸出 0徊哑,要么全部輸出 1熙兔,不會再出現(xiàn)一半 0 一半 1 的尷尬場面。

實例:

#!/usr/bin/python3

import threading

import time

class myThread (threading.Thread):

? ? def __init__(self, threadID, name, counter):

? ? ? ? threading.Thread.__init__(self)

? ? ? ? self.threadID = threadID

? ? ? ? self.name = name

? ? ? ? self.counter = counter

? ? def run(self):

? ? ? ? print ("開啟線程: " + self.name)

? ? ? ? # 獲取鎖浦译,用于線程同步

? ? ? ? threadLock.acquire()

? ? ? ? print_time(self.name, self.counter, 3)

? ? ? ? # 釋放鎖桃序,開啟下一個線程

? ? ? ? threadLock.release()

def print_time(threadName, delay, counter):

? ? while counter:

? ? ? ? time.sleep(delay)

? ? ? ? print ("%s: %s" % (threadName, time.ctime(time.time())))

? ? ? ? counter -= 1

threadLock = threading.Lock()

threads = []

# 創(chuàng)建新線程

thread1 = myThread(1, "Thread-1", 1)

thread2 = myThread(2, "Thread-2", 2)

# 開啟新線程

thread1.start()

thread2.start()

# 添加線程到線程列表

threads.append(thread1)

threads.append(thread2)

# 等待所有線程完成

for t in threads:

? ? t.join()

print ("退出主線程")

執(zhí)行以上程序杖虾,輸出結(jié)果為:

開啟線程: Thread-1

開啟線程: Thread-2

Thread-1: Wed Apr? 6 11:52:57 2016

Thread-1: Wed Apr? 6 11:52:58 2016

Thread-1: Wed Apr? 6 11:52:59 2016

Thread-2: Wed Apr? 6 11:53:01 2016

Thread-2: Wed Apr? 6 11:53:03 2016

Thread-2: Wed Apr? 6 11:53:05 2016

退出主線程

線程優(yōu)先級隊列( Queue)

Python 的 Queue 模塊中提供了同步的、線程安全的隊列類媒熊,包括 FIFO(先入先出)隊列 Queue奇适,LIFO(后入先出)隊列 LifoQueue,和優(yōu)先級隊列 PriorityQueue芦鳍。

這些隊列都實現(xiàn)了鎖原語嚷往,能夠在多線程中直接使用,可以使用隊列來實現(xiàn)線程間的同步怜校。

Queue 模塊中的常用方法:

Queue.qsize() 返回隊列的大小

Queue.empty() 如果隊列為空间影,返回 True,反之 False

Queue.full() 如果隊列滿了,返回 True,反之 False

Queue.full 與 maxsize 大小對應(yīng)

Queue.get([block[, timeout]]) 獲取隊列茄茁,timeout 等待時間

Queue.get_nowait() 相當 Queue.get(False)

Queue.put(item) 寫入隊列魂贬,timeout 等待時間

實例:

#!/usr/bin/python3

import queue

import threading

import time

exitFlag = 0

class myThread (threading.Thread):

? ? def __init__(self, threadID, name, q):

? ? ? ? threading.Thread.__init__(self)

? ? ? ? self.threadID = threadID

? ? ? ? self.name = name

? ? ? ? self.q = q

? ? def run(self):

? ? ? ? print ("開啟線程:" + self.name)

? ? ? ? process_data(self.name, self.q)

? ? ? ? print ("退出線程:" + self.name)

def process_data(threadName, q):

? ? while not exitFlag:

? ? ? ? queueLock.acquire()

? ? ? ? if not workQueue.empty():

? ? ? ? ? ? data = q.get()

? ? ? ? ? ? queueLock.release()

? ? ? ? ? ? print ("%s processing %s" % (threadName, data))

? ? ? ? else:

? ? ? ? ? ? queueLock.release()

? ? ? ? time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]

nameList = ["One", "Two", "Three", "Four", "Five"]

queueLock = threading.Lock()

workQueue = queue.Queue(10)

threads = []

threadID = 1

# 創(chuàng)建新線程

for tName in threadList:

? ? thread = myThread(threadID, tName, workQueue)

? ? thread.start()

? ? threads.append(thread)

? ? threadID += 1

# 填充隊列

queueLock.acquire()

for word in nameList:

? ? workQueue.put(word)

queueLock.release()

# 等待隊列清空

while not workQueue.empty():

? ? pass

# 通知線程是時候退出

exitFlag = 1

# 等待所有線程完成

for t in threads:

? ? t.join()

print ("退出主線程")

以上程序執(zhí)行結(jié)果:

開啟線程:Thread-1

開啟線程:Thread-2

開啟線程:Thread-3

Thread-3 processing One

Thread-1 processing Two

Thread-2 processing Three

Thread-3 processing Four

Thread-1 processing Five

退出線程:Thread-3

退出線程:Thread-2

退出線程:Thread-1

退出主線程

————————————————

版權(quán)聲明:本文為CSDN博主「沅沅說python」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議裙顽,轉(zhuǎn)載請附上原文出處鏈接及本聲明付燥。

原文鏈接:https://blog.csdn.net/qxr333000/article/details/120178026

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市愈犹,隨后出現(xiàn)的幾起案子键科,更是在濱河造成了極大的恐慌,老刑警劉巖漩怎,帶你破解...
    沈念sama閱讀 221,888評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件勋颖,死亡現(xiàn)場離奇詭異,居然都是意外死亡勋锤,警方通過查閱死者的電腦和手機饭玲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來叁执,“玉大人茄厘,你說我怎么就攤上這事√竿穑” “怎么了次哈?”我有些...
    開封第一講書人閱讀 168,386評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吆录。 經(jīng)常有香客問我窑滞,道長,這世上最難降的妖魔是什么恢筝? 我笑而不...
    開封第一講書人閱讀 59,726評論 1 297
  • 正文 為了忘掉前任哀卫,我火速辦了婚禮,結(jié)果婚禮上滋恬,老公的妹妹穿的比我還像新娘聊训。我一直安慰自己,他們只是感情好恢氯,可當我...
    茶點故事閱讀 68,729評論 6 397
  • 文/花漫 我一把揭開白布带斑。 她就那樣靜靜地躺著,像睡著了一般勋拟。 火紅的嫁衣襯著肌膚如雪勋磕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,337評論 1 310
  • 那天敢靡,我揣著相機與錄音挂滓,去河邊找鬼。 笑死啸胧,一個胖子當著我的面吹牛赶站,可吹牛的內(nèi)容都是我干的幔虏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,902評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼贝椿,長吁一口氣:“原來是場噩夢啊……” “哼想括!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起烙博,我...
    開封第一講書人閱讀 39,807評論 0 276
  • 序言:老撾萬榮一對情侶失蹤瑟蜈,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后渣窜,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體铺根,經(jīng)...
    沈念sama閱讀 46,349評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,439評論 3 340
  • 正文 我和宋清朗相戀三年乔宿,在試婚紗的時候發(fā)現(xiàn)自己被綠了位迂。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,567評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡予颤,死狀恐怖囤官,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蛤虐,我是刑警寧澤党饮,帶...
    沈念sama閱讀 36,242評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站驳庭,受9級特大地震影響刑顺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜饲常,卻給世界環(huán)境...
    茶點故事閱讀 41,933評論 3 334
  • 文/蒙蒙 一蹲堂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧贝淤,春花似錦柒竞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,420評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至离陶,卻和暖如春稼虎,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背招刨。 一陣腳步聲響...
    開封第一講書人閱讀 33,531評論 1 272
  • 我被黑心中介騙來泰國打工霎俩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 48,995評論 3 377
  • 正文 我出身青樓打却,卻偏偏與公主長得像杉适,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子学密,可洞房花燭夜當晚...
    茶點故事閱讀 45,585評論 2 359

推薦閱讀更多精彩內(nèi)容