在 Python 中進行多線程編程通常使用 threading
模塊。下面是一個簡單的示例,展示了如何創建和啟動多個線程。
示例代碼
import threading
import time# 定義一個簡單的函數,它將在線程中運行
def print_numbers():for i in range(10):print(f"Number: {i}")time.sleep(1)def print_letters():for letter in "abcdefghij":print(f"Letter: {letter}")time.sleep(1)# 創建線程對象
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)# 啟動線程
thread1.start()
thread2.start()# 等待線程完成
thread1.join()
thread2.join()print("All threads have finished execution")
代碼解釋
-
導入模塊:
import threading import time
threading
模塊提供了線程支持,而time
模塊用于在線程中引入延遲。 -
定義線程函數:
def print_numbers():for i in range(10):print(f"Number: {i}")time.sleep(1)def print_letters():for letter in "abcdefghij":print(f"Letter: {letter}")time.sleep(1)
這兩個函數將在不同的線程中運行,每個函數都會打印一個序列,并在每次打印后暫停一秒鐘。
-
創建線程對象:
thread1 = threading.Thread(target=print_numbers) thread2 = threading.Thread(target=print_letters)
threading.Thread
創建一個新的線程對象,target
參數指定線程應運行的函數。 -
啟動線程:
thread1.start() thread2.start()
調用
start()
方法以開始線程的執行。 -
等待線程完成:
thread1.join() thread2.join()
調用
join()
方法等待線程完成。這確保主程序在繼續執行之前等待所有線程結束。 -
線程完成后的打印語句:
print("All threads have finished execution")
這句在所有線程結束后打印確認信息。
注意事項
- 線程安全:在多線程編程中,如果多個線程同時訪問共享資源,可能會出現競爭條件,需要使用鎖(
threading.Lock
)來確保線程安全。 - GIL(全局解釋器鎖):由于 Python 的 GIL 的存在,多線程在 CPU 密集型任務中并不能真正并行執行,推薦使用
multiprocessing
模塊來繞過 GIL 限制以實現真正的并行執行。
如果你有更具體的需求或者需要處理更復雜的多線程任務,可以進一步探索 threading
模塊的其他功能,如 Lock
、Semaphore
、Event
等。