Python › Concurrency (asyncio/threading/multiprocessing)

What is a race condition, and how does it differ from a deadlock?

Intermediate

Answer

A race condition occurs when the outcome of concurrent operations depends on unpredictable timing, typically causing lost updates or corrupted shared state; a deadlock occurs when two or more threads/processes each hold a resource the other needs and wait forever, making no progress at all. Race conditions produce wrong results silently; deadlocks freeze the program entirely.
# Race condition: lost updates without a lock
counter = 0
def increment():
    global counter
    counter += 1  # not atomic: read, add, write can interleave between threads

# Deadlock: each thread waits on a lock the other holds
# Thread A: lock1.acquire(); lock2.acquire()
# Thread B: lock2.acquire(); lock1.acquire()  -- opposite order, can deadlock
Real-world example Debugging a counter that mysteriously undercounts under load (race condition) versus a service that hangs indefinitely under specific load patterns (deadlock).

Common follow-ups: What is the standard technique (like consistent lock ordering) for avoiding deadlocks in multi-lock code?