Concurrency bugs in review

Why two threads modifying the same data at the same time destroys it.

The idea

A Race Condition happens when two threads try to read and write to the same variable at the exact same time. The operation `count = count + 1` looks like one step, but to a CPU, it's three steps: 1) Read `count`, 2) Add 1, 3) Write `count`.

If Thread A and Thread B both read the value `10` at the same time, they will both calculate `11`, and both write `11`. The counter missed an increment! This is a Lost Update bug. We fix it by using a Lock (Mutex) to ensure only one thread can do the 3-step dance at a time.

Shared Count 10 Thread A Thread B Lock Held
Two threads want to run count = count + 1.

How it works (Check-then-Act)

# BAD: Race Condition
def increment_bad():
    current = db.get("count") # Thread A & B both get 10
    new_val = current + 1     # Thread A & B both calc 11
    db.set("count", new_val)  # Thread A & B both set 11. (Lost update!)

# GOOD: Mutex Lock
lock = Mutex()
def increment_good():
    with lock:
        # Thread B must wait here until Thread A finishes the block!
        current = db.get("count")
        new_val = current + 1
        db.set("count", new_val)