ZetCode

Python Lock

last modified November 29, 2026 Python 3.15

In this article we show how to protect shared data in Python threads with threading.Lock and threading.RLock.

Threads of one process share memory. When two threads read and modify the same data at the same time, the result depends on how their steps interleave. Such a bug is called a race condition. The part of the code that works with the shared data is a critical section.

A lock (also called a mutex) lets only one thread at a time enter a critical section. A Lock is either locked or unlocked. The acquire method locks it; if another thread already holds the lock, acquire blocks until that thread calls release.

Lost update

First we look at the problem a lock solves. Two threads deposit money to the same balance. Each reads the balance, does some work, and writes back the new value.

lost_update.py
import threading
import time

balance = 100


def deposit(amount):
    global balance
    current = balance
    time.sleep(0.1)
    balance = current + amount


t1 = threading.Thread(target=deposit, args=(50,))
t2 = threading.Thread(target=deposit, args=(30,))

t1.start()
t2.start()
t1.join()
t2.join()

print(f'expected 180, got {balance}')

The time.sleep call stands for any work done between reading and writing the shared value, such as a database query or a computation. It also makes the timing of the race predictable.

current = balance
time.sleep(0.1)
balance = current + amount

Both threads read the balance of 100 before either of them writes. The first thread writes 150, the second one writes 130 over it. The deposit of 50 is lost.

$ python lost_update.py
expected 180, got 130

Acquire and release

We fix the program by putting the read and the write into one critical section, guarded by a lock.

acquire_release.py
import threading
import time

balance = 100
lock = threading.Lock()


def deposit(amount):
    global balance
    lock.acquire()
    try:
        current = balance
        time.sleep(0.1)
        balance = current + amount
    finally:
        lock.release()


t1 = threading.Thread(target=deposit, args=(50,))
t2 = threading.Thread(target=deposit, args=(30,))

t1.start()
t2.start()
t1.join()
t2.join()

print(f'expected 180, got {balance}')

The second thread blocks in acquire until the first thread has written its result. Then it reads the updated balance.

lock.acquire()
try:
    ...
finally:
    lock.release()

The release call is placed in a finally clause. If the critical section raised an exception and the lock stayed locked, every other thread waiting for it would block forever.

$ python acquire_release.py
expected 180, got 180

The with statement

A lock is a context manager. The with statement acquires it at the start of the block and releases it at the end, also when an exception is raised. It is the usual way to use a lock.

with_lock.py
import threading
import time

balance = 100
lock = threading.Lock()


def deposit(amount):
    global balance
    with lock:
        current = balance
        time.sleep(0.1)
        balance = current + amount


start = time.perf_counter()

threads = [threading.Thread(target=deposit, args=(amount,))
           for amount in (50, 30, 20)]

for t in threads:
    t.start()

for t in threads:
    t.join()

elapsed = time.perf_counter() - start
print(f'balance: {balance}')
print(f'elapsed: {elapsed:.1f} s')

Three threads deposit to the balance. We also measure how long the program runs.

with lock:
    current = balance
    time.sleep(0.1)
    balance = current + amount

The block does the same as the acquire/try/finally code from the previous example. The program takes 0.3 seconds: the critical sections run one after another, not in parallel. A lock trades concurrency for correctness, so a critical section should be as short as possible.

$ python with_lock.py
balance: 200
elapsed: 0.3 s

A race without sleep

A race does not need a sleep call. The count += 1 statement looks like one step, but it reads the variable, adds one, and stores the result. Another thread can run between these steps.

counter_race.py
import threading

count = 0


def increment(n):
    global count
    for _ in range(n):
        count += 1


threads = [threading.Thread(target=increment, args=(100_000,))
           for _ in range(4)]

for t in threads:
    t.start()

for t in threads:
    t.join()

print(f'expected 400000, got {count}')

Four threads increment a shared counter 100,000 times each.

With the standard build of CPython, the global interpreter lock (GIL) lets only one thread execute Python code at a time and rarely switches threads in the middle of such a statement, so this program usually prints the expected value. That is luck, not a guarantee. The free-threaded build of Python (python3.15t) has no GIL and runs the threads truly in parallel. There most increments are lost, and the result differs on each run.

$ python3.15t counter_race.py
expected 400000, got 111461

Fixing the counter

The fix is the same as before: the increment becomes a critical section.

counter_lock.py
import threading

count = 0
lock = threading.Lock()


def increment(n):
    global count
    for _ in range(n):
        with lock:
            count += 1


threads = [threading.Thread(target=increment, args=(100_000,))
           for _ in range(4)]

for t in threads:
    t.start()

for t in threads:
    t.join()

print(f'expected 400000, got {count}')

The program is correct with and without the GIL. It is slower, because each increment now acquires and releases the lock.

with lock:
    count += 1

In real code it pays to do more work per lock acquisition. Each thread could count in a local variable and add the total to the shared counter once, at the end.

$ python3.15t counter_lock.py
expected 400000, got 400000

Lock state

The locked method tells whether a lock is held. The acquire method returns True when it gets the lock; with blocking=False it returns False at once instead of waiting.

lock_state.py
import threading

lock = threading.Lock()

print(lock.locked())
print(lock.acquire())
print(lock.locked())

print(lock.acquire(blocking=False))

lock.release()
print(lock.locked())

try:
    lock.release()
except RuntimeError as e:
    print(f'RuntimeError: {e}')

The program acquires the lock, tries to acquire it again without blocking, and releases it twice.

print(lock.acquire(blocking=False))

The lock is already held, so the non-blocking attempt fails. Note that a Lock does not remember its owner: if this call blocked, the thread would wait for itself forever.

try:
    lock.release()
except RuntimeError as e:

Releasing a lock that is not locked raises RuntimeError.

$ python lock_state.py
False
True
True
False
False
RuntimeError: release unlocked lock

Acquire with a timeout

The timeout parameter limits how long acquire waits. When the time runs out, it returns False.

lock_timeout.py
import threading
import time

lock = threading.Lock()


def backup():
    with lock:
        print('backup: started')
        time.sleep(1.5)
        print('backup: finished')


def report(name, timeout):
    time.sleep(0.1)
    if lock.acquire(timeout=timeout):
        try:
            print(f'{name}: got the lock')
        finally:
            lock.release()
    else:
        print(f'{name}: gave up after {timeout} s')


threads = [threading.Thread(target=backup),
           threading.Thread(target=report, args=('report-1', 0.5)),
           threading.Thread(target=report, args=('report-2', 2))]

for t in threads:
    t.start()

for t in threads:
    t.join()

A backup holds the lock for 1.5 seconds. Two reports want the lock while the backup is running; one waits at most half a second, the other two seconds.

if lock.acquire(timeout=timeout):
    try:
        print(f'{name}: got the lock')
    finally:
        lock.release()
else:
    print(f'{name}: gave up after {timeout} s')

The with statement cannot pass a timeout, so we call acquire directly. The lock is released only if it was acquired. The first report gives up; the second one gets the lock after the backup finishes.

$ python lock_timeout.py
backup: started
report-1: gave up after 0.5 s
backup: finished
report-2: got the lock

Check, then act

A lock must cover the whole operation, not only the write. If a thread checks a condition and then acts on it, another thread can change the data between the check and the action.

check_then_act.py
import threading
import time


class Account:

    def __init__(self, balance):
        self.balance = balance
        self._lock = threading.Lock()

    def withdraw(self, amount):
        with self._lock:
            if self.balance < amount:
                return False
            time.sleep(0.1)
            self.balance -= amount
            return True


acc = Account(100)
results = []


def buy(price):
    results.append(acc.withdraw(price))


threads = [threading.Thread(target=buy, args=(80,)) for _ in range(3)]

for t in threads:
    t.start()

for t in threads:
    t.join()

print(f'paid: {results.count(True)}, declined: {results.count(False)}')
print(f'balance: {acc.balance}')

Three threads try to withdraw 80 from an account with a balance of 100. Each Account object has its own lock, so operations on different accounts do not block each other.

with self._lock:
    if self.balance < amount:
        return False
    time.sleep(0.1)
    self.balance -= amount
    return True

The check and the withdrawal are in one critical section. Without the lock, all three threads would see a balance of 100, all three would pay, and the balance would end at -140. With the lock, one purchase succeeds and the other two are declined. Which thread wins can differ between runs; the totals do not.

$ python check_then_act.py
paid: 1, declined: 2
balance: 20

Deadlock

When a thread needs two locks, the order of acquisition matters. If one thread holds lock A and waits for lock B, while another thread holds B and waits for A, neither can continue. This is a deadlock.

deadlock.py
import threading
import time

lock_a = threading.Lock()
lock_b = threading.Lock()


def worker(name, first, second, timeout):
    with first:
        print(f'{name}: holds its first lock')
        time.sleep(0.1)
        if second.acquire(timeout=timeout):
            print(f'{name}: holds both locks')
            second.release()
        else:
            print(f'{name}: deadlock, giving up')


t1 = threading.Thread(target=worker, args=('t1', lock_a, lock_b, 1))
t2 = threading.Thread(target=worker, args=('t2', lock_b, lock_a, 2))

t1.start()
t2.start()
t1.join()
t2.join()

The two threads take the locks in opposite order. To keep the program from hanging, the second lock is acquired with a timeout.

t1 = threading.Thread(target=worker, args=('t1', lock_a, lock_b, 1))
t2 = threading.Thread(target=worker, args=('t2', lock_b, lock_a, 2))

Thread t1 holds A and waits for B; t2 holds B and waits for A. After one second t1 gives up and releases A, which lets t2 finish. Without the timeouts both threads would wait forever.

$ python deadlock.py
t1: holds its first lock
t2: holds its first lock
t1: deadlock, giving up
t2: holds both locks

Lock ordering

A timeout only detects a deadlock. The usual way to prevent one is to make every thread acquire locks in the same global order.

transfer.py
import threading
import time


class Account:

    def __init__(self, number, balance):
        self.number = number
        self.balance = balance
        self.lock = threading.Lock()


def transfer(src, dst, amount):
    first, second = sorted([src, dst], key=lambda acc: acc.number)
    with first.lock:
        time.sleep(0.1)
        with second.lock:
            src.balance -= amount
            dst.balance += amount


a = Account(1, 500)
b = Account(2, 300)

t1 = threading.Thread(target=transfer, args=(a, b, 100))
t2 = threading.Thread(target=transfer, args=(b, a, 50))

t1.start()
t2.start()
t1.join()
t2.join()

print(f'account 1: {a.balance}')
print(f'account 2: {b.balance}')
print(f'total: {a.balance + b.balance}')

Two transfers run at the same time in opposite directions between the same two accounts.

first, second = sorted([src, dst], key=lambda acc: acc.number)
with first.lock:
    time.sleep(0.1)
    with second.lock:

Both threads lock the account with the lower number first, whatever the direction of the transfer. The second thread waits for the first lock instead of grabbing the other one, so the cycle cannot form. The total amount of money is preserved.

$ python transfer.py
account 1: 450
account 2: 350
total: 800

Acquiring a lock twice

A Lock cannot be acquired again by the thread that holds it. This happens easily when a function that holds a lock calls another function that takes the same lock.

reentrant.py
import threading

lock = threading.Lock()


def outer():
    with lock:
        print('outer: holds the lock')
        inner()


def inner():
    if lock.acquire(timeout=1):
        print('inner: holds the lock')
        lock.release()
    else:
        print('inner: blocked by its own thread')


outer()

The outer function holds the lock and calls inner, which tries to acquire it too.

if lock.acquire(timeout=1):

The thread blocks on a lock it holds itself. Without the timeout, the program would hang.

$ python reentrant.py
outer: holds the lock
inner: blocked by its own thread

RLock

A reentrant lock, threading.RLock, can be acquired several times by the same thread. It counts the acquisitions and is unlocked only after the same number of releases. Other threads are blocked as with a plain lock.

rlock.py
import threading


class Inventory:

    def __init__(self):
        self._lock = threading.RLock()
        self._items = {}

    def add(self, name, qty):
        with self._lock:
            self._items[name] = self._items.get(name, 0) + qty

    def add_many(self, entries):
        with self._lock:
            for name, qty in entries:
                self.add(name, qty)

    def snapshot(self):
        with self._lock:
            return dict(self._items)

    def total(self):
        with self._lock:
            return sum(self._items.values())


inv = Inventory()
inv.add('apples', 4)
inv.add_many([('pears', 2), ('apples', 3), ('plums', 5)])

print(inv.snapshot())
print(inv.total())

All public methods of the Inventory class take the lock, and add_many calls add while holding it.

def add_many(self, entries):
    with self._lock:
        for name, qty in entries:
            self.add(name, qty)

The add_many method holds the lock for the whole batch, so other threads never see a half-added batch. The nested with in add succeeds because the same thread owns the lock. With a plain Lock the first call to add would deadlock.

$ python rlock.py
{'apples': 7, 'pears': 2, 'plums': 5}
14

Lock ownership

Unlike a Lock, an RLock has an owner: only the thread that acquired it may release it.

rlock_owner.py
import threading

lock = threading.Lock()
rlock = threading.RLock()

lock.acquire()
rlock.acquire()
rlock.acquire()


def release_both():
    lock.release()
    print('Lock released by another thread')
    try:
        rlock.release()
    except RuntimeError as e:
        print(f'RLock: RuntimeError: {e}')


t = threading.Thread(target=release_both)
t.start()
t.join()

rlock.release()
print(f'after one release: {rlock.locked()}')
rlock.release()
print(f'after two releases: {rlock.locked()}')

The main thread acquires a lock once and a reentrant lock twice. Then another thread tries to release both.

lock.release()
print('Lock released by another thread')

A plain Lock may be released by any thread. This is allowed, but it makes the code hard to follow; a Semaphore or an Event usually expresses such signalling better.

rlock.release()
print(f'after one release: {rlock.locked()}')

The other thread cannot release the reentrant lock. The main thread must release it as many times as it acquired it. The locked method of RLock was added in Python 3.14.

$ python rlock_owner.py
Lock released by another thread
RLock: RuntimeError: cannot release un-acquired lock
after one release: True
after two releases: False

Source

threading — Lock objects
threading — RLock objects
Python support for free threading

In this article we have protected shared data in Python threads with Lock and RLock. We have shown lost updates, critical sections with acquire, release and with, timeouts, the check-then-act problem, deadlocks and lock ordering. Locks for coroutines are shown in the asyncio article. Limiting the number of threads that use a resource is covered in Semaphore, and making threads wait for each other in Barrier.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.