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