Os Thread Race Condition
DodaTech
1 min read
In this tutorial, you'll learn about How to Fix Thread Race Condition Errors. We cover key concepts, practical examples, and best practices.
Fix thread race condition errors when shared variable increment without lock causes data loss.
Quick Fix
Wrong
import threading
cnt=0
def worker():
global cnt
for _ in range(100000): cnt+=1 # Not atomic!
ts=[threading.Thread(target=worker) for _ in range(10)]
[t.start() for t in ts]; [t.join() for t in ts]
print(cnt) # < 1000000 (lost updates)
cnt expected 1000000 but due to race condition gets ~500000-900000. Lost updates from non-atomic +=.
Right
import threading
lock=threading.Lock(); cnt=0
def worker():
global cnt
for _ in range(100000):
with lock: cnt+=1
ts=[threading.Thread(target=worker) for _ in range(10)]
[t.start() for t in ts]; [t.join() for t in ts]
print(cnt) # 1000000
1000000. Lock ensures mutual exclusion. One thread increments at a time.
Prevention
Use Lock for shared mutable state. Prefer threading primitives over relying on GIL.
DodaTech Tools
Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro