Python 線程模組快速指南及範例

王林
發布: 2024-09-12 14:17:31
原創
518 人瀏覽過

A Quick Guide to the Python threading Module with Examples

介紹

Python 中的線程模組提供了一個高級介面來創建和管理線程,使您能夠並發運行程式碼。這對於可以並行執行的任務(例如 I/O 密集型操作)特別有用。下面列出了 threading 模組中常用的方法和函數,並附有簡短的範例。

1. 線程()

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
登入後複製

2. 開始()

啟動執行緒的活動。

t = threading.Thread(target=print_numbers)
t.start()  # Runs the target function in a separate thread
登入後複製

3. 加入([超時])

阻塞呼叫線程,直到呼叫 join() 方法的線程終止。您可以選擇指定逾時。

t = threading.Thread(target=print_numbers)
t.start()
t.join(2)  # Waits up to 2 seconds for the thread to finish
登入後複製

4.is_alive()

如果執行緒仍在運行,則傳回 True。

t = threading.Thread(target=print_numbers)
t.start()
print(t.is_alive())  # True if the thread is still running
登入後複製

5. 當前線程()

傳回目前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
登入後複製

6. 枚舉()

傳回目前活動的所有 Thread 物件的清單。

t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)
t1.start()
t2.start()

print(threading.enumerate())  # Lists all active threads
登入後複製

7. 活動計數()

傳回目前存活的Thread物件的數量。

print(threading.active_count())  # Returns the number of active threads
登入後複製

8. 鎖定()

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()
登入後複製

9. RLock()

可重入鎖允許執行緒多次 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()
登入後複製

10. 條件()

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()
登入後複製

11. 事件()

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
登入後複製

12. 信號量()

信號量物件可讓您限制可以同時存取資源的執行緒數量。

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()
登入後複製

13.定時器(間隔、函數)

定時器執行緒在指定的時間間隔後執行函數。

def delayed_function():
    print("Executed after delay")

timer = threading.Timer(3, delayed_function)
timer.start()  # Executes `delayed_function` after 3 seconds
登入後複製

14. setDaemon(真)

守護執行緒在背景運行,並在主程式退出時自動退出。您可以透過呼叫 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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!