Python's
模組提供了兩個關鍵的同步工具:threading
和Lock
,均設計用於控制多執行緒應用程式中對共享資源的存取。 但是,它們的功能差異很大。 RLock
Lock
Lock
<code class="language-python">import threading lock = threading.Lock() def critical_section(): lock.acquire() try: print(f"{threading.current_thread().name} is accessing the shared resource.") finally: lock.release() thread1 = threading.Thread(target=critical_section) thread2 = threading.Thread(target=critical_section) thread1.start() thread2.start() thread1.join() thread2.join()</code>(threading.rlock)
RLock
>RLock
>
<code class="language-python">import threading rlock = threading.RLock() def recursive_task(count): rlock.acquire() try: print(f"{threading.current_thread().name} acquired the lock; count = {count}") if count > 0: recursive_task(count - 1) # Recursive call; re-acquires the lock finally: rlock.release() thread = threading.Thread(target=recursive_task, args=(3,)) thread.start() thread.join()</code>(threading.rlock)
Lock
和RLock
Feature |
Lock (threading.Lock) |
RLock (threading.RLock) |
---|---|---|
Reentrancy | Non-reentrant | Reentrant |
Use Case | Simple locking | Recursive/nested locking |
Performance | Generally faster | Slightly more overhead |
Lock
當處理遞歸功能或巢狀鎖定時,RLock
>選擇以上是R-Lock 與 Python 中的鎖的詳細內容。更多資訊請關注PHP中文網其他相關文章!