Why count += 1 isn't thread-safe in Python, GIL or not

Read the explanation
What if

Two threads read count, then both write old + 1. The second write lands on top of the first, so count ends at 1, on every build.

Predict first

Standard Python, GIL on. Both threads have read count (0) before either writes. What is count at the end?

012345678start a, bjoin()main: print count = 1printthread a: old = count (0)readthread a: both_read.wait()waitthread a: count = 0 + 1writeprintthread b: old = count (0)readthread b: count = 0 + 1writeprint

Tap any block to see what that thread is doing.

  • Running
  • Waiting / parked
Step 1/6

count starts at 0. main starts two threads, and each adds 1 to it.

1count = 02both_read = threading.Barrier(2)3 4def bump(name):5    global count6    old = count  # read7    both_read.wait()  # both have read before either writes8    count = old + 1  # write9    print(f"{name} wrote {old + 1}")10 11def main():12    a = threading.Thread(target=bump, args=("a",))13    b = threading.Thread(target=bump, args=("b",))14    a.start()15    b.start()16    a.join()17    b.join()18    print(f"count = {count}")19 20if __name__ == "__main__":21    main()

Explanation

What just happened

Both threads read count while it was still 0. Each then wrote 0 + 1, so the second write landed on top of the first. count ended at 1.

The barrier pins the unlucky moment so it happens every run. In real code a thread switch, or another core, lands between the read and the write only sometimes.

Try the what-if switch

Why the GIL doesn’t save you

Running in parallel and sharing safely are separate questions. The GIL decides how many threads run at once (see the GIL). It says nothing about which reads go with which writes.

When to use a lock

Whenever more than one thread changes the same value, and the new value depends on the old one.

Watch out

With the GIL, a plain count += 1 lost no update in our runs, so tests pass. On python3.15t it loses updates. Lock it now, before free-threading finds it.

Common questions

Is count += 1 thread-safe in Python?

No. It reads count, then writes a new value, and another thread can write in between. With a barrier between the two steps, count ends at 1 instead of 2 on every build.

Doesn't the GIL make it safe?

No. The GIL runs one thread at a time, but it doesn't keep a read and its write together. In our runs it hid the bug for a plain count += 1, while python3.15t lost updates.

How do I fix it?

Hold a threading.Lock around the read and the write. The second thread then reads what the first wrote, and count ends at 2 in every run.

Verified: this timeline matches a real program, checked in CI on Python 3.14, 3.15 and free-threaded 3.15t. How we verify. Unclear or wrong? Tell us