← Back to Home

🧵 Concurrency Fundamentals: Threads, Locks and Race Conditions

Threads, race conditions, locks, deadlocks, memory models and the GIL, with runnable Python and Go examples.

Since the mid-2000s, CPUs have gained cores instead of clock speed. A laptop today has 8–16 cores, and a server may have over a hundred. Using that hardware means doing several things at once, and doing several things at once is where some of the hardest bugs in software come from: wrong answers that appear one run in a thousand, systems that freeze with no error, and failures that disappear the moment you add a log line.

This article covers the core ideas: what concurrency is, why race conditions happen, how locks fix them, and how locks in turn cause deadlocks.

Concurrency is not parallelism

A web server handling 10,000 connections on one core is concurrent but not parallel. A matrix multiplication split across 16 cores is parallel. Most real systems are both. Rob Pike's summary is a good one: concurrency is about structure, parallelism is about execution.

Processes and threads

Process Thread
Memory Its own isolated address space Shares the address space of its process
Creation cost Higher (new page tables, file descriptors…) Lower
Communication Pipes, sockets, shared-memory segments Just read and write the same variables
Crash isolation A crash doesn't affect other processes A crash takes down the whole process
Danger Low Shared mutable state

Threads are cheap and can share data directly. That's both their advantage and their danger.

Race conditions

A race condition happens when the result depends on the unpredictable timing of threads. The classic example is a shared counter. counter += 1 looks like one step, but it's really three: read the value, add one, write it back. If two threads both read 5, both compute 6 and both write 6, one increment is lost.

import threading
import time

counter = 0

def work():
    global counter
    for _ in range(10_000):
        current = counter          # 1. read
        time.sleep(0)              #    (stand-in for real work: a log line, a DB call…)
        counter = current + 1      # 2. write, possibly overwriting another thread's update

threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(f"expected 40000, got {counter}")
# e.g. expected 40000, got 10004    (three quarters of the updates were lost)

The same bug in Go, without the pause:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	counter := 0
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 100_000; j++ {
				counter++ // data race: unsynchronized read-modify-write
			}
		}()
	}
	wg.Wait()
	fmt.Println("expected 400000, got", counter)
}

Run it a few times and you'll get 400000 on some runs and something like 359528 on others. That's what makes races dangerous: they often pass tests. Go's race detector finds them reliably:

$ go run -race main.go
==================
WARNING: DATA RACE
Read at 0x00c0000b6028 by goroutine 8:
  main.main.func1()
      main.go:16 +0x99

Previous write at 0x00c0000b6028 by goroutine 10:
  main.main.func1()
      main.go:16 +0xab

Run your Go tests with -race in CI. For C, C++ and Rust's unsafe code, ThreadSanitizer (-fsanitize=thread) does the same job.

Race conditions aren't limited to threads. Check-then-act races happen between processes and services too: two requests both check "is this username free?", both see yes, and both create it. The fix there is a unique constraint in the database, not a lock in your code.

Locks (mutexes)

A mutex (mutual exclusion lock) ensures only one thread at a time runs a critical section:

import threading
import time

counter = 0
lock = threading.Lock()

def work():
    global counter
    for _ in range(10_000):
        with lock:                 # only one thread at a time runs this block
            current = counter
            time.sleep(0)
            counter = current + 1

threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(f"expected 40000, got {counter}")    # expected 40000, got 40000

In Go, for a simple counter, use an atomic instead of a lock:

package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var wg sync.WaitGroup
	var counter atomic.Int64
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 100_000; j++ {
				counter.Add(1) // one indivisible CPU instruction
			}
		}()
	}
	wg.Wait()
	fmt.Println("expected 400000, got", counter.Load()) // always 400000
}

Locks have costs, so use them deliberately:

Deadlock

Locks fix races and introduce a new failure: deadlock, where threads wait for each other forever. The textbook case is two threads taking two locks in opposite order:

Thread A: lock(accounts)  … then wants lock(audit_log)
Thread B: lock(audit_log) … then wants lock(accounts)
→ A holds accounts and waits for audit_log; B holds audit_log and waits for accounts. Forever.

A deadlock needs all four Coffman conditions to hold at once:

  1. Mutual exclusion: a resource can be held by only one thread.
  2. Hold and wait: a thread holds one resource while waiting for another.
  3. No preemption: a resource can't be forcibly taken away.
  4. Circular wait: a cycle of threads, each waiting on the next.

Break any one of them and deadlock becomes impossible. The most practical fix is to break circular wait by always acquiring locks in the same global order:

import threading

lock_a, lock_b = threading.Lock(), threading.Lock()
ORDER = {id(lock_a): 0, id(lock_b): 1}      # one agreed order for every lock

def acquire_in_order(*locks):
    ordered = sorted(locks, key=lambda l: ORDER[id(l)])
    for l in ordered:
        l.acquire()
    return ordered

def transfer(first, second, name, log):
    held = acquire_in_order(first, second)  # callers may pass locks in any order
    try:
        log.append(name)
    finally:
        for l in reversed(held):
            l.release()

log = []
t1 = threading.Thread(target=transfer, args=(lock_a, lock_b, "A→B", log))
t2 = threading.Thread(target=transfer, args=(lock_b, lock_a, "B→A", log))
t1.start(); t2.start(); t1.join(); t2.join()
print(sorted(log))    # ['A→B', 'B→A'], both finished, no deadlock

Other options are lock timeouts (lock.acquire(timeout=1), which then requires retry logic) and avoiding the need for two locks at once.

Deadlocks also happen without explicit locks. A producer blocked writing to a full pipe while the consumer is blocked waiting on the producer is the same circular wait. That exact bug is walked through, with animations, in the Producer-Consumer Deadlock tutorial.

Coordinating threads

Mutual exclusion is only half the story. Threads also need to wait for each other:

Primitive What it does Typical use
Condition variable Sleep until another thread signals that something changed "Wait until the queue isn't empty"
Semaphore A counter of available permits Limit to 10 concurrent DB connections
Barrier Wait until N threads all arrive Phases of a parallel computation
Channel / queue Pass data between threads safely Producer-consumer pipelines

In most code, a thread-safe queue is the best tool. Instead of sharing state and locking it, threads pass messages:

import queue
import threading

jobs = queue.Queue(maxsize=100)     # bounded, so a fast producer blocks instead of using all memory
results = []

def worker():
    while (item := jobs.get()) is not None:
        results.append(item * item)
        jobs.task_done()
    jobs.task_done()

workers = [threading.Thread(target=worker) for _ in range(4)]
for w in workers: w.start()
for n in range(10):
    jobs.put(n)
for _ in workers:
    jobs.put(None)                  # one stop signal per worker
jobs.join()
print(sorted(results))              # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Go puts this idea at the center of the language: "Don't communicate by sharing memory; share memory by communicating." Channels are queues built into the language.

Memory models: why "it should be fine" isn't

On modern hardware, threads don't necessarily see each other's writes in the order they happened. Compilers reorder instructions, CPUs execute out of order, and each core has its own caches. So this pattern is broken in C, C++, Java and Go without proper synchronization:

Thread 1:                Thread 2:
data = 42                while !ready { }
ready = true             print(data)       // may print 0, or loop forever

A language's memory model defines which reorderings are allowed and which operations create a happens-before relationship: lock/unlock, atomic operations, channel sends and receives, thread start and join. The practical rule is simple: if two threads access the same variable and at least one writes it, synchronize with a lock, an atomic, or a channel. Don't try to reason your way around it.

Python and the GIL

CPython has a Global Interpreter Lock: only one thread runs Python bytecode at a time. As a result:

This is changing: Python 3.13 introduced an optional free-threaded build without the GIL (PEP 703), and Python 3.14 made it officially supported, though it's still a separate build and not the default.

How much faster can it get? Amdahl's law

If a fraction p of a program can run in parallel on n cores, the best possible speedup is:

speedup = 1 / ((1 − p) + p / n)

With 90% parallel code on 16 cores, that's 1 / (0.1 + 0.9/16) ≈ 6.4×, not 16×. Even with infinite cores, it can never exceed 10×. The serial part dominates. Before adding threads, find out what can't be parallelized: a single lock, a single database, a single-threaded step.

Practical rules

  1. Avoid shared mutable state. Prefer immutable data, message passing and queues.
  2. When you must share, protect every access, reads included, with one clear lock or an atomic.
  3. Acquire multiple locks in a fixed order, and never hold a lock across I/O.
  4. Use the highest-level tool that works: thread pools, concurrent.futures, channels, asyncio for I/O (Async I/O and Event Loops).
  5. Test with race detectors (go test -race, ThreadSanitizer) and under load.
  6. Push correctness into the database for cross-service races: unique constraints, transactions, SELECT … FOR UPDATE.

Concurrency bugs are hard to reproduce, so the goal is code where they can't happen in the first place.

Copied to clipboard!