1. 程式人生 > >十分鐘帶你瞭解 Python3 多執行緒核心知識

十分鐘帶你瞭解 Python3 多執行緒核心知識

每個獨立的執行緒有一個程式執行的入口、順序執行序列和程式的出口。但是執行緒不能夠獨立執行,必須依存在應用程式中,由應用程式提供多個執行緒執行控制。

每個執行緒都有他自己的一組CPU暫存器,稱為執行緒的上下文,該上下文反映了執行緒上次執行該執行緒的CPU暫存器的狀態。

指令指標和堆疊指標暫存器是執行緒上下文中兩個最重要的暫存器,執行緒總是在程序得到上下文中執行的,這些地址都用於標誌擁有執行緒的程序地址空間中的記憶體。

執行緒可以被搶佔(中斷)。
在其他執行緒正在執行時,執行緒可以暫時擱置(也稱為睡眠) – 這就是執行緒的退讓。
執行緒可以分為:

核心執行緒:由作業系統核心建立和撤銷。
使用者執行緒:不需要核心支援而在使用者程式中實現的執行緒。
Python3 執行緒中常用的兩個模組為:

_thread
threading(推薦使用)
函式式
呼叫 _thread 模組中的start_new_thread()函式來產生新執行緒。語法如下:

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

引數說明:

function - 執行緒函式。
args - 傳遞給執行緒函式的引數,他必須是個tuple型別。
kwargs - 可選引數。

import _thread, time

定義執行緒函式

def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
# 返回當前時間的時間戳(1970紀元後經過的浮點秒數), 並格式化輸出
print("{}: {}".format(threadName, time.ctime(time.time()) ))
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

E:\PyPro>python thread.py
Thread-1: Thu Apr 12 09:01:56 2018
Thread-2: Thu Apr 12 09:01:58 2018
Thread-1: Thu Apr 12 09:01:58 2018
Thread-1: Thu Apr 12 09:02:00 2018
Thread-2: Thu Apr 12 09:02:02 2018
Thread-1: Thu Apr 12 09:02:02 2018
Thread-1: Thu Apr 12 09:02:05 2018
Thread-2: Thu Apr 12 09:02:06 2018
Thread-2: Thu Apr 12 09:02:10 2018
Thread-2: Thu Apr 12 09:02:14 2018

類封裝式
threading 模組除了包含 _thread 模組中的所有方法外,還提供的其他方法:

threading.currentThread(): 返回當前的執行緒變數。
threading.enumerate(): 返回一個包含正在執行的執行緒的list。正在執行指執行緒啟動後、結束前,不包括啟動前和終止後的執行緒。
threading.activeCount(): 返回正在執行的執行緒數量,與len(threading.enumerate())有相同的結果。
執行緒模組同樣提供了Thread類來處理執行緒,Thread類提供了以下方法:

run(): 用以表示執行緒活動的方法。
start():啟動執行緒活動。
join([time]): 等待至執行緒中止。這阻塞呼叫執行緒直至執行緒的join() 方法被呼叫中止-正常退出或者丟擲未處理的異常-或者是可選的超時發生。
isAlive(): 返回執行緒是否活動的。
getName(): 返回執行緒名。
setName(): 設定執行緒名。

import threading, time

建立程序類

class myThread(threading.Thread):

建構函式

def init(self, threadID, name, counter):
threading.Thread.init(self)
self.threadID = threadID
self.name = name
self.counter = counter

重寫run()

def run(self):
print(“Thread Strat:” + self.name)
print_time(self.name, self.counter, 5)
print(“Thread Exit:” + self.name)

def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("{}: {}".format(threadName, time.ctime(time.time()) ))
counter -= 1

建立執行緒

thread1 = myThread(1001, “Thread-1”, 1)
thread2 = myThread(1002, “Thread-2”, 2)

開啟執行緒

print("Thread-1 is Alive? ", thread1.isAlive())
thread1.start()
thread2.start()
print("Thread-1 is Alive? ", thread1.isAlive())
thread1.join()
thread2.join()
print("Thread-1 is Alive? ", thread1.isAlive())
print(“exit”)

E:\PyPro>python threadClass.py
Thread-1 is Alive? False
Thread Strat:Thread-1
Thread Strat:Thread-2
Thread-1 is Alive? True
Thread-1: Thu Apr 12 10:15:53 2018
Thread-1: Thu Apr 12 10:15:54 2018
Thread-2: Thu Apr 12 10:15:54 2018
Thread-1: Thu Apr 12 10:15:55 2018
Thread-1: Thu Apr 12 10:15:56 2018
Thread-2: Thu Apr 12 10:15:56 2018
Thread-1: Thu Apr 12 10:15:57 2018
Thread Exit:Thread-1
Thread-2: Thu Apr 12 10:15:58 2018
Thread-2: Thu Apr 12 10:16:00 2018
Thread-2: Thu Apr 12 10:16:02 2018
Thread Exit:Thread-2
Thread-1 is Alive? False
exit

不難發現,執行緒是通過start()函式啟用,而不是物件建立時啟用的!

執行緒同步
多執行緒的優勢在於可以同時執行多個任務(至少感覺起來是這樣)。但是當執行緒需要共享資料時,可能存在資料不同步的問題。

使用 Thread 物件的 Lock 和 Rlock 可以實現簡單的執行緒同步,這兩個物件都有 acquire 方法和 release 方法,對於那些需要每次只允許一個執行緒操作的資料,可以將其操作放到 acquire 和 release 方法之間。

import threading, time

建立鎖

threadLock = threading.Lock()

建立執行緒列表

threads = []

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("Thread Start: " + self.name)
# 獲取鎖,同步執行緒
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 釋放鎖,開啟下一個執行緒
threadLock.release()
print("Thread Exit: " + self.name)

def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("{}: {}".format(threadName, time.ctime()))
counter -= 1

建立執行緒

thread1 = myThread(1001, “Thread-1”, 1)
thread2 = myThread(1002, “Thread-2”, 2)

開啟執行緒

thread1.start()
thread2.start()

新增執行緒列表

threads.append(thread1)
threads.append(thread2)

等待所有執行緒完成

for t in threads:
t.join()
print(“exit”)

E:\PyPro>python synchronize.py
Thread Start: Thread-1
Thread Start: Thread-2
Thread-1: Thu Apr 12 11:00:49 2018
Thread-1: Thu Apr 12 11:00:50 2018
Thread-1: Thu Apr 12 11:00:51 2018
Thread Exit: Thread-1
Thread-2: Thu Apr 12 11:00:53 2018
Thread-2: Thu Apr 12 11:00:55 2018
Thread-2: Thu Apr 12 11:00:57 2018
Thread Exit: Thread-2
exit

執行緒優先順序佇列
Python 的 Queue 模組中提供了同步的、執行緒安全的佇列類,包括FIFO佇列Queue,LIFO佇列LifoQueue,和優先順序佇列 PriorityQueue。

這些佇列都實現了鎖原語,能夠在多執行緒中直接使用,可以使用佇列來實現執行緒間的同步。

Queue 模組中的常用方法:

Queue.qsize() 返回佇列的大小
Queue.empty() 如果佇列為空,返回True,反之False
Queue.full() 如果佇列滿了,返回True,反之False
Queue.full 與 maxsize 大小對應
Queue.get([block[, timeout]])獲取佇列,timeout等待時間
Queue.get_nowait() 相當Queue.get(False)
Queue.put(item) 寫入佇列,timeout等待時間
Queue.put_nowait(item) 相當Queue.put(item, False)
Queue.task_done() 在完成一項工作之後,Queue.task_done()函式向任務已經完成的佇列傳送一個訊號
Queue.join() 實際上意味著等到佇列為空,再執行別的操作

import queue, threading, time

exitFlag = 0

建立鎖

queueLock = threading.Lock()

建立佇列

workQueue = queue.Queue(10)

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("Thread Start: " + self.name)
process_data(self.name, self.q)
print("Thread Exit: " + self.name)

def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print("{} processing {}".format(threadName, data))
else:
queueLock.release()
time.sleep(1)

threadList = [“Thread-1”, “Thread-2”, “Thread-3”]
nameList = [“One”, “Two”, “Three”, “Four”, “Five”]
threads = []
threadID = 1

建立新執行緒

for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1

填充佇列

queueLock.acquire()
print(“佇列填充中>>>>>>>>>>>>>>”)
time.sleep(1)
for word in nameList:
workQueue.put(word)
print(“佇列填充完畢>>>>>>>>>>>>>>”)
queueLock.release()

等待佇列清空

while not workQueue.empty():
pass

通知執行緒退出

exitFlag = 1

等待所有執行緒完成

for t in threads:
t.join()
print(“exit”)

E:\PyPro>python queueue.py
Thread Start: Thread-1
Thread Start: Thread-2
Thread Start: Thread-3
佇列填充中>>>>>>>>>>>>>>
佇列填充完畢>>>>>>>>>>>>>>
Thread-3 processing One
Thread-1 processing Two
Thread-2 processing Three
Thread-3 processing Four
Thread-1 processing Five
Thread Exit: Thread-2
Thread Exit: Thread-1
Thread Exit: Thread-3
exit

原始碼中其實實現了三個程序讀取同一個佇列,按照先進先出原則實現鎖定。

用start方法來啟動執行緒,真正實現了多執行緒執行,這時無需等待run方法體程式碼執行完畢而直接繼續執行下面的程式碼。通過呼叫Thread類的start()方法來啟動一個執行緒,這時此執行緒處於就緒(可執行)狀態,並沒有執行,一旦得到cpu時間片,就開始執行run()方法,這裡方法 run()稱為執行緒體,它包含了要執行的這個執行緒的內容,Run方法執行結束,此執行緒隨即終止。

join的作用是保證當前執行緒執行完成後,再執行其它執行緒。join可以有timeout引數,表示阻塞其它執行緒timeout秒後,不再阻塞。。一般執行緒的start()之後,所有操作結束後都要進行thread.join()。確保語句的輸出是join()後面的程式是等執行緒結束後再執行的。

作者:Eappo_Geng
來源:https://my.oschina.net/gain/blog/1794659