一、線程管理
在多線程編程中,線程管理是一個非常重要的部分。在Python中,線程可以通過Thread類進行創建和控制。
import threading
import time
def worker():
print("Worker start.")
time.sleep(5)
print("Worker end.")
t1 = threading.Thread(target=worker)
t1.start()
上面的代碼通過Thread類創建了一個名叫t1的線程,並傳入了worker函數作為線程的執行函數。執行t1.start()後,該線程就開始執行了。在這個例子中,worker函數是一個簡單的模擬耗時操作的函數,執行5秒後就結束。當線程執行完成後,Python解釋器並不會自動將其銷毀,需要調用t1.join()方法等待線程執行完畢,或者調用t1.is_alive()方法判斷線程是否還在執行。
二、線程式控制制
線程式控制制是多線程編程中的關鍵部分,可以通過一些方法對線程進行控制,比如等待線程執行完成、終止線程等。
1.等待線程執行完成
在多線程編程中,常見的需求就是等待所有子線程執行完成之後再進行後續操作,可以通過遍歷所有線程來實現。
import threading
import time
def worker():
print("Worker start.")
time.sleep(5)
print("Worker end.")
threads = []
for i in range(5):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for t in threads:
t.join()
print("All workers done.")
上面的代碼中,創建了5個線程並掛起,每個線程執行5秒後結束。在創建完所有線程之後,遍歷所有線程並執行t.join()等待線程執行完畢。執行完畢後會列印出”All workers done.”。
2.終止線程
終止線程是一種非常危險的操作,只有在必要時才應該使用。可以通過設置線程的stop標誌位或者調用線程的terminate()方法來終止線程。
(1)設置stop標誌位
可以通過設置線程的stop標誌位,來令線程主動結束。
import threading
import time
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self.stop = False
def run(self):
print("Thread start.")
while not self.stop:
print("Thread is running.")
time.sleep(1)
print("Thread end.")
def stop_thread(self):
self.stop = True
t = MyThread()
t.start()
time.sleep(5)
t.stop_thread()
上面的代碼中,自定義了一個MyThread類,線程執行的代碼在run方法中。run方法通過檢查stop標誌位來判斷線程是否應該結束,並在需要時結束線程。當需要結束線程時,調用MyThread的stop_thread方法,將stop標誌位設置為True即可。
(2)調用terminate()方法
還可以直接調用線程的terminate()方法來終止線程,但是該方法很危險,應該在必要時才使用。因為線程在執行過程中可能會持有鎖或者其他資源,在線程被突然終止的情況下,可能會導致這些資源被永久佔用。
import threading
import time
def worker():
print("Worker start.")
while True:
print("Worker is running.")
time.sleep(1)
t = threading.Thread(target=worker)
t.start()
time.sleep(5)
t.terminate() # 終止線程
三、線程同步
在多線程編程中,線程之間可能會存在一些共享資源,如果多個線程同時對這些資源進行讀寫,就可能導致數據不一致或者異常情況。為了解決這個問題,需要使用線程同步機制來協調多個線程的操作。
1.Lock對象
Lock對象可以用來協調多個線程對臨界區的訪問。臨界區就是指多個線程都要訪問的共享資源區域,需要在訪問該區域之前獲取鎖,訪問完畢後釋放鎖。
import threading
import time
class SharedResource:
def __init__(self):
self.lock = threading.Lock()
self.count = 0
def increment(self):
with self.lock:
self.count += 1
print("SharedResource: ", self.count)
def worker(resource):
for i in range(5):
resource.increment()
time.sleep(1)
resource = SharedResource()
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(resource,))
t.start()
threads.append(t)
for t in threads:
t.join()
print("All workers done.")
上面的代碼中,自定義了一個SharedResource類,該類維護了一個共享計數器count。increment方法對計數器進行加1操作,並使用with鎖語句獲取鎖,避免多個線程同時修改計數器。在worker函數中創建了3個線程,並讓每個線程調用5次increment方法,每次調用前都會獲取鎖進行保護。執行完畢後列印”All workers done.”。
2.Condition對象
Condition對象也可以用來協調多個線程的訪問。與Lock對象不同的是,Condition對象可以在特定變數滿足某些條件時,釋放所有等待該條件的線程,也可以在某個條件被滿足時喚醒所有等待的線程。
import threading
import time
class SharedResource:
def __init__(self):
self.lock = threading.Lock()
self.condition = threading.Condition(self.lock)
self.count = 0
def increment(self):
with self.lock:
self.count += 1
print("SharedResource: ", self.count)
if self.count >= 5:
self.condition.notify_all()
def wait(self):
with self.lock:
while self.count < 5:
self.condition.wait()
def worker(resource):
for i in range(5):
resource.increment()
time.sleep(1)
resource.wait()
resource = SharedResource()
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(resource,))
t.start()
threads.append(t)
for t in threads:
t.join()
print("All workers done.")
上面的代碼中,SharedResource類中增加了wait方法,並在increment方法中增加了一個判斷,當計數器達到5時,調用notify_all方法喚醒所有等待該條件的線程。在worker函數中,每個線程執行5次increment方法後,會調用wait方法等待條件滿足。最後的列印”All workers done.”會在所有線程都執行完畢並完成條件等待後列印。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/247165.html