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
- with a lock: the read and the write happen under one lock, so the second thread reads 1 and writes 2.
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