Skip to content

Python Threading Race Condition Fix

DodaTech Updated 2026-06-24 3 min read

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 (or RLock) when multiple threads access shared mutable state.
  • Use with lock: context manager -- never manually call acquire()/release().
  • Minimize shared state by passing copies of data to threads.
  • Use queue.Queue for thread-safe communication.
  • Use threading.local() for thread-scoped data that does not need sharing.

Common Mistakes with threading race

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. 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

### What is a race condition?

A race condition occurs when the behavior of software depends on the timing of uncontrollable events like thread scheduling. The result changes unpredictably when threads interleave in different orders.

Why does counter += 1 cause a race condition?

counter += 1 is three operations: read the value, add one, write the result. A thread can read a stale value if another thread writes between the read and the write, causing lost updates.

What is the difference between Lock and RLock?

Lock is a simple mutual exclusion lock. RLock (reentrant lock) can be acquired multiple times by the same thread without deadlocking, useful when a function calls another function that acquires the same lock.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro