Python 中的線程模組提供了一個高級介面來創建和管理線程,使您能夠並發運行程式碼。這對於可以並行執行的任務(例如 I/O 密集型操作)特別有用。下面列出了 threading 模組中常用的方法和函數,並附有簡短的範例。
Thread 類別是執行緒模組的核心。您可以使用此類建立和啟動新線程。
import threading def print_numbers(): for i in range(5): print(i) t = threading.Thread(target=print_numbers) t.start() # Starts a new thread t.join() # Waits for the thread to finish
啟動執行緒的活動。
t = threading.Thread(target=print_numbers) t.start() # Runs the target function in a separate thread
阻塞呼叫線程,直到呼叫 join() 方法的線程終止。您可以選擇指定逾時。
t = threading.Thread(target=print_numbers) t.start() t.join(2) # Waits up to 2 seconds for the thread to finish
如果執行緒仍在運行,則傳回 True。
t = threading.Thread(target=print_numbers) t.start() print(t.is_alive()) # True if the thread is still running
傳回目前Thread對象,代表呼叫執行緒。
import threading def print_current_thread(): print(threading.current_thread()) t = threading.Thread(target=print_current_thread) t.start() # Prints the current thread info
傳回目前活動的所有 Thread 物件的清單。
t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_numbers) t1.start() t2.start() print(threading.enumerate()) # Lists all active threads
傳回目前存活的Thread物件的數量。
print(threading.active_count()) # Returns the number of active threads
Lock 物件是一個原始鎖,用於防止競爭條件。您可以使用它來確保一次只有一個執行緒存取共享資源。
lock = threading.Lock() def thread_safe_function(): with lock: # Acquires the lock # Critical section print("Thread-safe code") t = threading.Thread(target=thread_safe_function) t.start()
可重入鎖允許執行緒多次 acquire() 鎖,而不會阻塞自身。
lock = threading.RLock() def reentrant_function(): with lock: with lock: # Same thread can acquire the lock again print("Reentrant lock example") t = threading.Thread(target=reentrant_function) t.start()
Condition 物件允許執行緒等待滿足某些條件。
condition = threading.Condition() def thread_wait(): with condition: condition.wait() # Wait for the condition print("Condition met") def thread_notify(): with condition: condition.notify() # Notify the waiting thread t1 = threading.Thread(target=thread_wait) t2 = threading.Thread(target=thread_notify) t1.start() t2.start()
Event 物件用於在執行緒之間發出訊號。一個線程可以等待事件被設置,另一個線程可以設定事件。
event = threading.Event() def wait_for_event(): event.wait() # Wait until the event is set print("Event has been set") t = threading.Thread(target=wait_for_event) t.start() event.set() # Set the event to allow the thread to continue
信號量物件可讓您限制可以同時存取資源的執行緒數量。
semaphore = threading.Semaphore(2) # Only 2 threads can access the resource at once def access_resource(): with semaphore: print("Resource accessed") t1 = threading.Thread(target=access_resource) t2 = threading.Thread(target=access_resource) t3 = threading.Thread(target=access_resource) t1.start() t2.start() t3.start()
定時器執行緒在指定的時間間隔後執行函數。
def delayed_function(): print("Executed after delay") timer = threading.Timer(3, delayed_function) timer.start() # Executes `delayed_function` after 3 seconds
守護執行緒在背景運行,並在主程式退出時自動退出。您可以透過呼叫 setDaemon(True) 或將 daemon=True 傳遞給 Thread 建構子來讓執行緒成為守護程式。
t = threading.Thread(target=print_numbers, daemon=True) t.start() # Daemon thread will exit when the main program ends
threading 模組是 Python 中處理並發的強大工具。它提供了多個類別和方法來創建和控制線程,從而可以輕鬆並行執行程式碼。從使用基本的 Thread 物件到使用 Lock 和 Semaphore 管理同步,該模組對於編寫並發 Python 程式至關重要。
以上是Python 線程模組快速指南及範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!