On this page
threading.Lock
Prev: threading.local | Up: threading | Next: threading.main_thread
Rel: threading.active_count, threading.Barrier, threading.BoundedSemaphore, threading.BrokenBarrierError
Ref: docs.python.org — threading.Lock
Tags: #public #python3 #stdlib #threading
Import
import threading
from threading import Lock
Signature & Overview
threading.Lock()
A lock object is a synchronization primitive. To create a lock, call threading.Lock(). Methods are: acquire() -- lock the lock, possibly blocking until it can be obtained
Methods & Attributes
Lock.acquire(self, /, blocking=True, timeout=-1)— Lock the lock. Without argument, this blocks if the lock is already locked (even by the same thread), waiting for another thread to release the lock, and return True once the lock is acquired.Lock.acquire_lock(self, /, blocking=True, timeout=-1)— An obsolete synonym of acquire().Lock.locked(self, /)— Return whether the lock is in the locked state.Lock.locked_lock(self, /)— An obsolete synonym of locked().Lock.release(self, /)— Release the lock, allowing another thread that is blocked waiting for the lock to acquire the lock. The lock must be in the locked state, but it needn't be locked by the same thread that unlocks it.Lock.release_lock(self, /)— An obsolete synonym of release().
Usage
import threading
lock = threading.Lock()
counter = 0
def inc() -> None:
global counter
for _ in range(1000):
with lock:
counter += 1
threads = [threading.Thread(target=inc) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
assert counter == 4000
Gotchas
- Always use
with lock:: Guarantees release even when an exception is raised inside the critical section. - Non-reentrant: Calling
lock.acquire()twice in the same thread deadlocks—useRLockif a thread needs to re-enter.
REPL Inspect
from threading import Lock
help(Lock)
Linked from
Related notes
- tuts/python3/stdlib_module/threading/local Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/main_thread Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/active_count Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Barrier Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BoundedSemaphore Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BrokenBarrierError Linked here; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Condition shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/current_thread shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/enumerate shared tags: #stdlib, #threading