Locks, atomics and deadlocks
Two threads that touch the same data can quietly break it. Locks and atomics stop that, and lock order stops the deadlocks that locks can cause.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
This is a made-up example, but the bug in it is real. A team runs a small API that counts video views. Each request starts a thread, and each thread runs views = views + 1 on a shared counter in memory. In tests, 1,000 requests give 1,000 views.
In production, traffic is high and the server has many CPU cores. The dashboard shows fewer views than the access logs. The gap is small, so nobody notices for weeks. There is no error and no stack trace.
The bug is easy to reproduce. The OSTEP textbook runs two threads that each add 1 to a shared counter 10 million times. The answer should be 20,000,000. 1
Sometimes the book gets the right answer. But one run gave 19,345,221, and the next gave 19,221,041. 1 Wrong totals that change from run to run are the mark of a race condition. In this lesson you will see why it happens, and the tools that fix it.
The idea in simple words
views = views + 1 looks like one step. OSTEP shows that on x86 it becomes three instructions: load the value into a register, add 1, and store it back. 1
If the scheduler switches threads between those steps, two threads can load the same old value. 1 Both store the same new value. One add is lost.
OSTEP calls this a race condition: the result depends on the timing of the threads. The code that touches shared data is a critical section. It must not run in more than one thread at a time. 1
The key idea. Shared data that changes needs one of three things: a lock, so only one thread is inside at a time; an atomic operation, so the change cannot be split; or no sharing at all.
How it works
Step through the lost update, then the two fixes. Use Next and Back, or the ← and → keys.
- The counter is 7. Thread A runs counter = counter + 1. The CPU does this in three steps: load, add, store. A loads 7 into its register.
- Before A stores its result, the scheduler switches to Thread B. B runs the same line and also loads 7.
- A adds 1 to its own copy and stores 8.
- B adds 1 to its old copy, 7, and also stores 8. It overwrites A's work. Two adds ran, but the counter grew by one. This is a lost update.
- Fix 1: a lock around the line. B must wait until A unlocks, so it loads 8 and stores 9. Fix 2: one atomic add. The load, add and store happen as one step that nobody can split.
Mutexes and locks
A mutex (mutual exclusion lock) has two states, locked and unlocked. In Python, acquire() on a locked lock blocks until another thread calls release(). 9 Go's sync.Mutex works the same way. 7
Put the critical section between lock and unlock:
mu.Lock()
views = views + 1
mu.Unlock()Keep the critical section short. Never do a network call or slow disk read while you hold a lock. Every other thread that needs it waits.
Atomics and compare-and-swap
For one number, a lock is often more than you need. Java's AtomicLong and AtomicInteger have atomic increment methods. 4 Go has atomic.AddInt64. 8
The base tool under many of these is compare-and-swap (CAS). Go's docs describe it as one atomic step: if the value still equals old, set it to new and return true; otherwise return false. 8 Java calls it compareAndSet. 4
With CAS you read the value, compute the new one, and try to swap. If another thread changed it first, the swap fails and you try again. OSTEP shows how locks themselves are built from instructions like this. 2
Go warns that its atomic functions "require great care to be used correctly". Outside low-level code, it suggests channels or the sync package instead. 8
Read-write locks
Many readers can safely read at the same time. Only writers need to be alone. A read-write lock allows many readers or one writer. 5
Java's docs say the gain is fully seen only on a multi-processor, and only when data is read often and changed rarely. If reads are very short, the extra cost of the lock can eat the gain. 5 Go also warns against taking a read lock again while you hold one. A waiting writer blocks new readers. 7
Deadlock
Locks bring a new risk. Thread 1 holds lock A and waits for lock B. Thread 2 holds B and waits for A. Neither can move. This is a deadlock.
OSTEP lists four conditions, which it credits to a 1971 paper by Coffman, Elphick and Shoshani. All four must hold for a deadlock: 3
- Mutual exclusion. A thread has a resource, such as a lock, to itself.
- Hold and wait. A thread holds some locks while it waits for more.
- No preemption. Nobody can take a lock away from its holder.
- Circular wait. There is a cycle of threads, each waiting for a lock the next one holds.
Break any one condition and deadlock cannot happen. 3
Lock ordering breaks circular wait. Decide a global order, for example "always lock A before B". OSTEP calls this probably the most practical way to prevent deadlock. 3
Try, then back off. OSTEP shows a thread that cannot get its second lock. It releases the first lock and starts again. The book discusses this under no preemption. 3 In Python, acquire(timeout=2) returns False if it cannot get the lock in 2 seconds. 9
Livelock and starvation
- Livelock: threads keep trying and backing off, but none makes progress. OSTEP suggests a random delay before each retry. 3
- Starvation: one thread never gets the lock, because others always win. Simple spin locks are not fair and can cause it. 2
The same ideas in a database
A database has the same problems, one level up. Two requests that read a row, add 1 in app code, and write it back can lose an update. The transactions lesson shows the fixes: one atomic UPDATE, or a row lock with SELECT … FOR UPDATE.
Row locks can deadlock too. The Postgres docs show two transactions that update the same two accounts in opposite order. Postgres detects the deadlock and aborts one of them. Which one is hard to predict. 10
The fix is the same as in memory. Postgres says the best defence is to take locks on many objects in a consistent order. 10 You can also set lock_timeout, so a statement stops instead of waiting too long for a lock. 11 More in locking and MVCC in practice.
Across machines
A mutex works only inside one process. When many servers share one job, you need a distributed lock. Kleppmann says it should expire after a time, so a crashed client cannot hold it forever. A lock with a timeout is called a lease. 12
Leases have a trap. Martin Kleppmann describes a client that pauses for garbage collection. Its lease expires, another client takes the lock, and then the first client wakes up and writes anyway. 12
His fix is a fencing token: a number that grows each time the lock is given out. The storage rejects any write with an older token than one it has already seen. 12 He also asks: is the lock for efficiency or for correctness? If two nodes doing the same work only costs a little, a simple lock on one Redis node is enough. 12 Redis in depth covers Redlock and the debate about it. See leader election and leases and Raft.
Prefer higher-level tools
Go's sync docs say higher-level synchronization is better done with channels. 7 Java gives you thread pools and blocking queues for producer-consumer designs. 6
The best lock is the one you do not need. Give each piece of data one owner, for example one worker reading from a queue. Pass immutable values between threads. Actors, covered in threads, async and actors, follow the same idea.
Trade-offs
| Tool | Good for | Cost | Watch out for |
|---|---|---|---|
| Mutex | Any critical section, many variables at once. | Threads wait. Slow if held long. | Deadlock, forgotten unlock. |
| Atomic / CAS | One counter or one reference. | Retries under heavy contention. | Two atomics together are not atomic. |
| Read-write lock | Many reads, rare writes. | More complex than a mutex. | Little gain on one core. Busy readers can delay a writer for a long time. |
| Database row lock | Shared rows across many app servers. | Waiting transactions, deadlock aborts. | Lock order, lock_timeout, retries. |
| Lease (distributed lock) | One worker per job across machines. | A lock service to run. | Expiry during a pause. Needs fencing for correctness. |
| Queue or single owner | No shared changing data at all. | Extra hop, ordering design. | A slow consumer becomes the bottleneck. |
At work: how a senior uses this
- When you see shared state that changes, ask "who else writes this?" first. This one question finds many race bugs.
- Prefer no sharing, then atomics for one value, then a mutex. Use a read-write lock only after a profile shows it helps.
- Write the lock order down in a comment or in the design doc, and keep it the same in every code path.
- Never call the network or wait on I/O while you hold a lock.
- Run your tests with a race detector where the language has one.
- In SQL, update rows in a fixed order, for example by ID, and retry on deadlock errors.
- For a distributed lock, ask whether it is for efficiency or for correctness. For correctness, use fencing tokens, or better, a database constraint.
- When a bug "only happens under load" and the numbers are a little off, suspect a race condition.
With AI
What to ask the agent
"Here is our Go service. List every variable that more than one goroutine can write. For each, say how it is protected today, and suggest the simplest safe fix."
"This Java class uses two locks. Draw the order in which each method takes them, and tell me if any pair of methods can deadlock."
"Write a test that runs this counter code with 8 threads and 1 million increments each, and fails if the total is wrong."
What to check yourself
- The agent's fix protects every read and write of the shared data, not just one of them.
- A "thread-safe" claim is tested with many threads and many runs, not one run.
- No lock is held across a network call or a callback.
- Two separate atomic operations were not treated as one atomic step.
- Code that uses a distributed lock for correctness also has fencing or a database check.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 12 sources and related lessons
- Remzi and Andrea Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 26, “Concurrency: An Introduction” (opens in a new tab)
Two threads add to a shared counter 10 million times each and get a different wrong total on each run. Defines race condition and critical section. - Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 28, “Locks” (opens in a new tab)
How locks are built from hardware instructions such as compare-and-swap, and why simple spin locks can starve a thread. - Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 32, “Common Concurrency Problems” (opens in a new tab)
The four conditions for deadlock from Coffman, Elphick and Shoshani (1971), lock ordering, livelock, and a study of real concurrency bugs. - Java SE 21 API: package java.util.concurrent.atomic (opens in a new tab)
AtomicInteger, AtomicLong and compareAndSet for lock-free, thread-safe updates of one variable. - Java SE 21 API: interface ReadWriteLock (opens in a new tab)
Many readers or one writer, and when that really helps. - Java SE 21 API: package java.util.concurrent (opens in a new tab)
Thread pools and blocking queues for producer-consumer designs. - Go standard library: package sync (opens in a new tab)
Mutex and RWMutex, and the advice to prefer channels for higher-level work. - Go standard library: package sync/atomic (opens in a new tab)
What compare-and-swap and atomic add do, and the warning that they need great care. - Python documentation: threading — Lock objects (opens in a new tab)
Lock.acquire with a timeout, and using a lock with the with statement. - PostgreSQL documentation: Explicit Locking (Deadlocks) (opens in a new tab)
A deadlock between two UPDATEs on two rows, how Postgres breaks it, and why a consistent lock order prevents it. - PostgreSQL documentation: Client Connection Defaults (lock_timeout) (opens in a new tab)
lock_timeout stops a statement that waits too long for a lock. - Martin Kleppmann, “How to do distributed locking” (2016) (opens in a new tab)
Locks for efficiency versus correctness, leases that expire during a pause, and fencing tokens.
Related: OS essentials for backend engineers · Transactions and isolation levels · Locking and MVCC in practice · Lock-free programming and memory models (coming soon) · Concurrency models: threads, async and actors (coming soon) · Leader election and leases
Next: Lock-free programming and memory models goes deeper into CAS loops and memory visibility. OSTEP's chapter on common concurrency bugs is free and short.