Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 13 / Topic 3 of 11

Shared data and race conditions

Threads share memory, so two threads can change the same variable. A race condition is a bug where the result depends on which thread happens to run first. The classic one is a lost update: two threads read the same old value, and one write overwrites the other. Like two people updating one shared notebook: both read "₹0", both write "₹100", and one deposit vanishes.

import threading
import time

balance = 0

def deposit(amount: int) -> None:
    global balance
    current = balance           # 1. read
    time.sleep(0.01)            # 2. a small pause: another thread runs now
    balance = current + amount  # 3. write (overwrites the other thread's work)

threads = [threading.Thread(target=deposit, args=(100,)) for _ in range(5)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
print(balance)    # 100   (expected 500! usually 100, can vary)

The fix: threading.Lock

A lock lets only one thread at a time into a piece of code (the critical section). Others wait at the door. Always use it with with, so it is released even if an error happens.

import threading
import time

balance = 0
lock = threading.Lock()

def deposit(amount: int) -> None:
    global balance
    with lock:                  # take the lock; others wait here
        current = balance
        time.sleep(0.01)
        balance = current + amount
    # the lock is released here, even after an exception

threads = [threading.Thread(target=deposit, args=(100,)) for _ in range(5)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
print(balance)    # 500

Keep the locked part small: while one thread holds the lock, the others do nothing.

Producer–consumer with queue.Queue

Often one part of a program makes work (the producer) and other parts do it (the consumers). queue.Queue is a thread-safe line of items: put() adds to the back, get() takes from the front and waits if the queue is empty. It does its own locking, so you don't need a Lock. Like a restaurant: waiters pin order slips on a rail, and cooks take the next slip when they are free.

import queue
import threading

orders: queue.Queue = queue.Queue()
STOP = None          # a "sentinel": a special value that means "no more work"

def cook() -> None:
    while True:
        dish = orders.get()          # waits until there is an order
        if dish is STOP:
            break
        print("cooked", dish)

worker = threading.Thread(target=cook)
worker.start()
for dish in ["dosa", "idli", "vada"]:
    orders.put(dish)                 # the main thread is the producer
orders.put(STOP)
worker.join()
# cooked dosa
# cooked idli
# cooked vada

With several consumers, put one STOP per consumer.

Full programs: examples/02_race_and_lock.py (lost update vs lock) and examples/03_producer_consumer.py (one waiter, two cooks).

🔍 Going deeper: even counter += 1 is a read-then-write, so it is not safe across threads. It may look fine on your computer and fail on another one. If threads share data and at least one writes, use a lock or a queue.

Done here? The practice set for Part 13 — 8 exercises with solutions — is on the part page.

Search the guide