Python的多線程編程在實際應用中扮演著很重要的角色,能夠大大提升程序的性能,縮短運行時間,改善用戶體驗。在Python中,我們可以使用Thread類來實現多線程編程,它提供了簡單易用的介面,讓我們很容易地利用多線程實現並發任務處理。在這篇文章中,我們將從以下幾個方面詳細介紹如何利用Thread實現多線程編程。
一、Thread類簡介
Thread類是Python中多線程編程的核心類,使用它我們可以很容易地創建和管理多個線程。在Python中,每個線程都是一個Thread類的實例,每個線程都有一個唯一的標識符,我們可以通過該標識符來區分不同的線程。Thread類提供了以下幾個常用方法:
Thread(target=None, args=(), kwargs={})
start()
run()
join([timeout])
①Thread()方法:創建一個新線程,可設置線程的目標函數、位置參數和關鍵字參數。
②start()方法:啟動線程,使其處於就緒狀態。
③run()方法:定義線程的功能,通過覆蓋該方法來編寫線程的功能代碼。
④join()方法:等待線程終止。
二、多線程編程實戰
1、利用Thread實現多線程編程
下面是一個簡單的例子,利用Thread類實現並發任務處理。
import threading
import time
def job():
for i in range(5):
print "Thread:", threading.current_thread().name, " Processing:", i
time.sleep(1)
if __name__ == '__main__':
threads = []
for i in range(3):
t = threading.Thread(target=job)
t.start()
threads.append(t)
for t in threads:
t.join()
print "All threads done!"
執行結果如下所示:
Thread: Thread-1 Processing: 0
Thread: Thread-2 Processing: 0
Thread: Thread-3 Processing: 0
Thread: Thread-1 Processing: 1
Thread: Thread-2 Processing: 1
Thread: Thread-3 Processing: 1
Thread: Thread-1 Processing: 2
Thread: Thread-2 Processing: 2
Thread: Thread-3 Processing: 2
Thread: Thread-1 Processing: 3
Thread: Thread-2 Processing: 3
Thread: Thread-3 Processing: 3
Thread: Thread-1 Processing: 4
Thread: Thread-2 Processing: 4
Thread: Thread-3 Processing: 4
All threads done!
上述代碼中,首先定義一個job函數,它用於模擬一個需要執行的任務,在任務中我們使用了time.sleep()模擬任務的執行時間。然後創建一個含有3個線程的線程池,並且將job函數作為線程的目標函數,並啟動線程。最後,使用join()方法等待所有線程執行完畢。
2、利用Thread實現線程池
在實際開發中,我們可能需要創建大量的線程來處理任務,但是線程的創建和銷毀代價很高,為了減少這種開銷,我們可以使用線程池來管理線程。下面是一個基於Thread類實現的簡單線程池示例。
import threading
import time
class ThreadPool(object):
def __init__(self, max_threads):
self.max_threads = max_threads
self._threads = []
self._lock = threading.Lock()
def apply_async(self, func, *args, **kwargs):
self._lock.acquire()
try:
if len(self._threads) >= self.max_threads:
raise Exception("Max threads exceeded")
t = threading.Thread(target=func, args=args, kwargs=kwargs)
t.start()
self._threads.append(t)
finally:
self._lock.release()
def join(self):
for t in self._threads:
t.join()
def job(i):
print "Thread:", threading.current_thread().name, " Processing:", i
time.sleep(1)
if __name__ == '__main__':
pool = ThreadPool(3)
for i in range(9):
pool.apply_async(job, i)
pool.join()
print "All threads done!"
執行結果如下所示:
Thread: Thread-1 Processing: 0
Thread: Thread-2 Processing: 1
Thread: Thread-3 Processing: 2
Thread: Thread-4 Processing: 3
Thread: Thread-5 Processing: 4
Thread: Thread-6 Processing: 5
Thread: Thread-7 Processing: 6
Thread: Thread-8 Processing: 7
Thread: Thread-9 Processing: 8
All threads done!
上述代碼中,我們首先創建了一個ThreadPool類,它包含了最大線程數、線程列表和鎖等屬性。然後定義了apply_async()和join()兩個方法,apply_async()函數用於向線程池中加入新的線程,並啟動線程執行指定的任務;join()函數通過join()方法等待所有線程執行完畢。最後,我們使用ThreadPool類創建了一個含有3個線程的線程池,並向線程池中加入了9個任務,最後使用join()方法等待所有任務都完成。
三、多線程編程實戰技巧
1、避免共享資源衝突
在多線程編程中,經常會涉及到共享資源的訪問,例如多個線程需要同時訪問同一個列表,這時就需要注意避免資源衝突問題。
import threading
class Counter(object):
def __init__(self):
self.num = 0
self.lock = threading.Lock()
def add(self, n):
self.lock.acquire()
try:
self.num += n
finally:
self.lock.release()
if __name__ == '__main__':
c = Counter()
t1 = threading.Thread(target=c.add, args=(1,))
t2 = threading.Thread(target=c.add, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
print "counter:", c.num
執行結果如下所示:
counter: 3
上述代碼中,我們定義了一個Counter類,它含有一個num屬性和一個鎖。在add函數中,我們使用了鎖來確保對共享資源的訪問不會引起衝突。在程序運行時,我們創建了兩個線程分別執行add函數,最後使用join()方法等待所有線程執行完畢,並輸出結果。
2、線程間通信
在多線程編程中,線程間通信是非常常見的需求,例如生產者和消費者問題、信號量等。Python提供了一些用於線程間通信的模塊,例如Queue、Condition、Event等。下面是一個簡單的利用Queue實現線程間通信的示例。
import threading
import time
import Queue
class Consumer(threading.Thread):
def __init__(self, name, queue):
threading.Thread.__init__(self)
self.name = name
self.queue = queue
def run(self):
while True:
if self.queue.qsize() > 0:
item = self.queue.get()
print "Consumer %s get item %s" % (self.name, item)
class Producer(threading.Thread):
def __init__(self, name, queue):
threading.Thread.__init__(self)
self.name = name
self.queue = queue
def run(self):
for i in range(5):
item = "item" + str(i)
self.queue.put(item)
print "Producer %s put item %s" % (self.name, item)
time.sleep(1)
if __name__ == '__main__':
queue = Queue.Queue(10)
p1 = Producer("P1", queue)
p2 = Producer("P2", queue)
c1 = Consumer("C1", queue)
c2 = Consumer("C2", queue)
p1.start()
p2.start()
c1.start()
c2.start()
p1.join()
p2.join()
c1.join()
c2.join()
print "All threads done!"
執行結果如下所示:
Producer P1 put item item0
Consumer C1 get item item0
Producer P2 put item item1
Consumer C2 get item item1
Producer P1 put item item2
Consumer C2 get item item2
Producer P2 put item item3
Consumer C1 get item item3
Producer P1 put item item4
Consumer C2 get item item4
All threads done!
上述代碼中,我們創建了一個含有10個位置的隊列,並定義了Producer和Consumer兩個類分別用於生產者和消費者的線程執行。在Producer的run()方法中,我們向隊列中放入5個item;在Consumer的run()方法中,我們使用了queue.qsize()方法判斷隊列是否為空,如果不為空,則獲取隊列中的item並輸出;最後使用join()方法等待所有線程執行完畢,並輸出結果。
總結
本文介紹了Python多線程編程的一些知識和實踐技巧,重點講解了Thread類的使用、線程池的實現、共享資源衝突的避免、線程間通信等方面的內容。希望本文能夠對大家在實際開發中的多線程編程有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/235596.html