Python Threading Race Condition Fix
In this tutorial, you'll learn about Python Threading Race Condition Fix. We cover key concepts, practical examples, and best practices.
Threading race conditions occur when two or more threads read and write shared data concurrently without proper synchronization. The result depends on thread scheduling order, producing non-deterministic bugs that are hard to reproduce and debug.
The Wrong Way
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
counter += 1
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Final counter: {counter}")
print(f"Expected: {500000}")
Output:
Final counter: 284159
Expected: 500000
The counter is never correct because counter += 1 is not atomic.
The Right Way
Use a threading.Lock to protect access to shared state:
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with lock:
counter += 1
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Final counter: {counter}")
Output:
Final counter: 500000
Step-by-Step Fix
1. Identify shared mutable state
Find variables, lists, dicts, or objects that are read and written by multiple threads.
2. Add locks around critical sections
lock = threading.Lock()
shared_data = {}
def thread_safe_update(key, value):
with lock:
shared_data[key] = value
3. Use threading.RLock for reentrant locking
rlock = threading.RLock()
def outer():
with rlock:
inner()
def inner():
with rlock: # Would deadlock with Lock, works with RLock
pass
4. Replace shared state with thread-local data
import threading
local_data = threading.local()
def worker():
local_data.count = 0
for _ in range(1000):
local_data.count += 1
print(f"Thread {threading.current_thread().name}: {local_data.count}")
5. Use queue.Queue for producer-consumer patterns
from queue import Queue
from threading import Thread
def producer(q):
for i in range(10):
q.put(i)
def consumer(q):
while True:
item = q.get()
if item is None:
break
print(f"Got: {item}")
q = Queue()
Thread(target=producer, args=(q,)).start()
Thread(target=consumer, args=(q,)).start()
Prevention Tips
- Always use
threading.Lock(orRLock) when multiple threads access shared mutable state. - Use
with lock:context manager -- never manually callacquire()/release(). - Minimize shared state by passing copies of data to threads.
- Use
queue.Queuefor thread-safe communication. - Use
threading.local()for thread-scoped data that does not need sharing.
Common Mistakes with threading race
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro