Python › Concurrency (asyncio/threading/multiprocessing)

How do you protect shared mutable state from race conditions when using multiple threads, using threading.Lock?

Intermediate

Answer

Wrap the critical section (code that reads-then-writes shared state) in 'with lock:' — this ensures only ONE thread can execute that block at a time, preventing the classic race condition where two threads interleave their read/modify/write operations and lose an update.
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    with lock:
        counter += 1  # protected: no race condition between threads

threads = [threading.Thread(target=increment) for _ in range(1000)]
for t in threads: t.start()
for t in threads: t.join()
print(counter)  # reliably 1000, not less due to lost updates
Real-world example Safely incrementing a shared counter or updating a shared cache from multiple worker threads without data corruption.

Common follow-ups: What would happen to the final counter value if the lock were removed entirely, and why?