Python Glossary Русский

all Python 3threadingterm

threading.Lock

synchronization

The mutual exclusion primitive (a mutex). It guarantees that only one thread at a time runs the protected block of code.

Syntax

lock = threading.Lock()
lock.acquire() / lock.release()
with lock: ...

Lock is non-reentrant: if the same thread tries to acquire it a second time without releasing the first (in recursion, or a nested method under the same lock), it deadlocks itself forever — that exact case is why RLock exists. Always take it via with lock:, or an exception inside the block leaves the lock held and other threads hang.

Examples

import threading
lock = threading.Lock()
counter = 0
def increment():
    global counter
    with lock:          # автоматический release
        counter += 1
threads = [threading.Thread(target=increment) for _ in range(100)]
for t in threads: t.start()
for t in threads: t.join()
print(counter)  # 100

See also

Open in the full glossarydocs.python.orgReport an inaccuracy