Course contentsShow
← Python
Lesson 864 of 1,06014. Concurrency and PerformanceFree lesson

Ensuring Atomicity with Mutual Exclusion Locks

Implement threading.Lock to create critical sections that ensure only one thread modifies a shared resource at any given time.

In this lesson, you will learn how to synchronize thread access to shared resources using mutual exclusion locks to prevent data corruption.

When multiple threads operate concurrently in Python, they often compete to read or modify the same object in memory. Without coordination, you face race conditions, where the final state of your data depends on the unpredictable timing of thread execution. If two threads read a shared counter, increment it, and write it back simultaneously, one increment might be overwritten, causing your data to lose its atomicity.

Implementing a Critical Section with threading.Lock

To ensure that only one thread accesses a shared resource at a time, we use a threading.Lock. The code block where the modification occurs is called a critical section. By acquiring the lock before entering this section and releasing it immediately after, we force other threads to wait in line, ensuring the operation is "atomic"—meaning it appears to happen as a single, indivisible step.

Consider a shared bank balance:

import threading

balance = 0
balance_lock = threading.Lock()

def update_balance(amount):
    global balance
    # The critical section starts here
    with balance_lock:
        current = balance
        balance = current + amount
    # The lock is automatically released here

# Spawning threads to safely update the balance
threads = [threading.Thread(target=update_balance, args=(10,)) for _ in range(100)]
for t in threads: t.start()
for t in threads: t.join()

print(f"Final balance: {balance}")

Why Use with?

Using the with statement (the context manager) is best practice. If an exception occurs within the critical section, the context manager guarantees the lock is released. If you were to manually call lock.acquire() and lock.release(), an error could leave the lock in a permanent "acquired" state, causing a deadlock where all other threads are blocked indefinitely.

By wrapping your shared resource access in these locks, you ensure that even though your code is concurrent, your data operations remain strictly serialized and consistent.

Key Takeaway: Mutual exclusion locks act as a gatekeeper, ensuring that only one thread can execute a critical section of code at any time, effectively preventing race conditions and maintaining data integrity.