Python 3 -多線程編程
隨著互聯網的普及和計算機技術的不斷發展,現在我們的電腦可以一邊看視頻,一邊打游戲,同時還可以開著瀏覽器、文本編輯器等等。愛掏網 - it200.com這就要歸功于多線程技術。愛掏網 - it200.com多線程是一種讓計算機同時處理多個任務的技術,可以提高程序運行的效率,尤其是對于網絡編程,因為可以同時處理多個網絡請求,從而提高服務器的處理能力,降低用戶等待的時長。愛掏網 - it200.comPython 3提供了豐富的多線程編程方法,本文將介紹Python 3中的多線程編程,供讀者學習和參考。愛掏網 - it200.com
Python 3中提供了兩種多線程模塊:thread和threading,其中,thread模塊已經被廢棄,使用threading模塊可以更好的進行多線程編程。愛掏網 - it200.com
使用threading模塊需要導入該模塊,代碼如下:
import threading
通過創建線程對象并啟動線程,來運行多線程程序。愛掏網 - it200.com創建線程對象的方法有兩種:
- 通過繼承Thread類創建線程
import threading
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 ("退出線程:" + self.name)
# 創建新線程
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
# 開啟新線程
thread1.start()
thread2.start()
print ("退出主線程")
- 通過直接調用Thread類的構造函數創建線程
import threading
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % (threadName, time.ctime(time.time())))
# 創建新線程
thread1 = threading.Thread(target=print_time, args=("Thread-1", 1))
thread2 = threading.Thread(target=print_time, args=("Thread-2", 2))
# 開啟新線程
thread1.start()
thread2.start()
print ("退出主線程")
多線程的基本操作
啟動線程
在Python 3中,啟動線程有兩種方法:繼承Thread類和直接創建Thread對象。愛掏網 - it200.com使用Thread類方法時,只需要在創建線程對象時設定要執行的函數;而使用直接創建Thread對象的方法時,需要將要執行的函數作為target參數來傳遞。愛掏網 - it200.com
import threading
# 定義執行的函數
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % (threadName, time.ctime(time.time())))
# 使用繼承Thread類方法創建線程
class MyThread (threading.Thread):
def __init__(self, threadID, name, counter, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.delay = delay
def run(self):
print ("開始線程:" + self.name)
print_time(self.name, self.delay)
print ("退出線程:" + self.name)
# 創建新線程
thread1 = MyThread(1, "Thread-1", 1, 1)
thread2 = MyThread(2, "Thread-2", 2, 2)
# 開啟新線程
thread1.start()
thread2.start()
print ("退出主線程")
線程同步
多線程編程中,線程之間會相互干擾,甚至導致數據錯誤,因此需要進行線程同步。愛掏網 - it200.comPython 3中提供了Lock、RLock、Semaphore、Event等同步機制。愛掏網 - it200.com
Lock
Lock類是最基本的同步原語,提供了多線程操作時的排他性。愛掏網 - it200.com在需要使用共享資源的代碼塊中,程序可以調用acquire()方法獲得鎖,當程序執行完畢后,使用release()方法釋放鎖。愛掏網 - it200.com
import threading
lock = threading.Lock()
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)
# 獲取鎖
lock.acquire()
print_time(self.name, self.counter)
# 釋放鎖
lock.release()
print ("退出線程:" + self.name)
# 創建新線程
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
# 開啟新線程
thread1.start()
thread2.start()
print ("退出主線程")
RLock
RLock類是可重入鎖,即允許一個線程多次獲取同一個鎖,其方式與Lock類相同。愛掏網 - it200.com
import threading
lock = threading.RLock()
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)
lock.acquire()
print_time(self.name, self.counter)
lock.release()
print ("退出線程:"+self.name)
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
print ("退出主線程")
Semaphore
Semaphore類是允許多個線程同時訪問一定數量資源的同步機制,通常用于限制同時訪問一個資源的線程數量。愛掏網 - it200.com
import threading
semaphore = threading.Semaphore(2)
class MyThread (threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print ("開始線程:"+ self.name)
semaphore.acquire()
print_time(self.name, self.delay)
semaphore.release()
print ("退出線程:"+self.name)
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
thread3 = MyThread(3, "Thread-3", 3)
thread1.start()
thread2.start()
thread3.start()
print ("退出主線程")
Event
Event類用于線程之間的通信,一個線程通知另一個線程某個事件發生。愛掏網 - it200.com一個線程可以等待事件,也可以重置事件。愛掏網 - it200.com
import threading
event = threading.Event()
class MyThread (threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print ("開始線程:" + self.name)
# 等待事件
event.wait()
print_time(self.name, self.delay)
print ("退出線程:" + self.name)
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
time.sleep(2)
# 事件觸發
event.set()
print ("退出主線程")
線程優先級
線程在執行時,可能會強制停止,轉而執行其他線程的操作,這就是線程優先級。愛掏網 - it200.com線程優先級在Python 3中可以設置,但是既使設置了優先級,也不能完全按照優先級執行,因為Python 3沒有提供嚴格的優先級保證。愛掏網 - it200.com
在Python 3中,線程的優先級有三個等級:LOWEST、LOW、NORMAL、HIGH、HIGHEST,使用threading模塊中Thread類的set_priority()函數可以進行設置。愛掏網 - it200.com默認情況下,所有線程都是NORMAL級別的。愛掏網 - it200.com
import threading
class MyThread (threading.Thread):
def __init__(self, threadID, name, priority):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.priority = priority
def run(self):
print ("開始線程:" + self.name)
print_time(self.name, self.priority)
print ("退出線程:" + self.name)
thread1 = MyThread(1, "Thread-1", threading.ThreadPriority.HIGHEST)
thread2 = MyThread(2, "Thread-2", threading.ThreadPriority.LOW)
thread1.start()
thread2.start()
print ("退出主線程")
多線程的應用和注意事項
線程池
線程池是一種常見的線程管理方式,它可以控制線程數量的上限,并且重復利用已經創建的線程。愛掏網 - it200.com線程池的優點在于減少線程的創建和銷毀開銷,同時提高程序的可伸縮性,降低程序的資源占用等。愛掏網 - it200.com
在Python 3中,可以使用ThreadPoolExecutor 類來實現線程池,代碼如下:
from concurrent.futures import ThreadPoolExecutor
import threading
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % (threadName, time.ctime(time.time())))
# 創建線程池
threadPool = ThreadPoolExecutor(max_workers=2)
# 提交任務
future1 = threadPool.submit(print_time, "Thread-1", 1)
future2 = threadPool.submit(print_time, "Thread-2", 2)
# 等待任務完成
future1.result()
future2.result()
print ("退出主線程")
注意事項
- 多線程編程需要考慮線程的安全性和同步性,對臨界資源進行保護,避免競爭條件的出現。愛掏網 - it200.com
- 多線程編程需要考慮資源的分配,合理的分配線程,避免創建過多的線程導致資源的浪費。愛掏網 - it200.com
- 多線程編程在處理I/O密集型任務中會遇到一些問題,如果線程的數量多了,很有可能會降低性能,使用協程的方式來解決這個問題。愛掏網 - it200.com
結論
Python 3提供了多種多樣的多線程編程方法,可以方便地實現多線程編程,提高程序的效率。愛掏網 - it200.com本文介紹了Python 3中的多線程模塊,以及多線程的基本操作、同步、優先級設置、線程池和注意事項。愛掏網 - it200.com希望本文可以對Python 3多線程編程感興趣的讀者提供一些參考和幫助。愛掏網 - it200.com