Concurrency
When two pieces of code use the same data at the same time, the result can depend on luck. Learn to see race conditions and deadlocks, fix them with a lock or an atomic database update, and avoid shared data when you can.
Author: bezzad
Contents
The problem: one phone, two buyers
Our online shop has a flash sale. Only one phone is left in stock. The web app serves requests with several threads. The code is:
stock = {"phone-x": 1}
def buy(product_id: str) -> bool:
if stock[product_id] > 0: # check
charge_customer() # takes some time
stock[product_id] -= 1 # act
return True
return False
- In tests one user buys the phone. It works.
- On sale day two users click “Buy” at the same moment. Both pay. Both get a “Thank you” page. But we have only one phone, and now the stock is -1.
Each line is correct. The problem is timing: two threads ran the same lines at the same time, on the same data.
A few words first
- Concurrency means several tasks are in progress at the same time. They may take turns on one CPU core.
- Parallelism means several tasks really run at the same moment, on several CPU cores.
- A process is a running program. Each process has its own memory.
- A thread runs inside a process. All threads of one process share the same memory. This is useful, and it is also the source of the danger.
Race condition: when luck decides
A race condition happens when the result depends on the order in which threads run.
The smallest example is a counter. “Add one” looks like one step, but it is really three:
- Read the current value.
- Add one to it.
- Write the result back.
If one thread is paused between step 1 and step 3, another thread can read the old value. Then one of the updates is lost.
Try it yourself. The demo below runs two threads that each add one to a counter 1,000 times.
Each thread adds one to the counter 1,000 times. Each addition is three steps: read, add, write. The scheduler can switch threads between any two steps.
Our phone bug is the same family. It is called check-then-act: we check a condition (“stock is above zero”), and later we act on it (“take one from stock”). Between the check and the act, another thread can change the data. The slow charge_customer call in the middle makes this gap wide.
Fix 1: a lock
A lock lets only one thread at a time run a piece of code. This piece of code is called the critical section.
import threading
stock = {"phone-x": 1}
stock_lock = threading.Lock()
def buy(product_id: str) -> bool:
with stock_lock:
if stock[product_id] <= 0:
return False
stock[product_id] -= 1 # reserve the item
charge_customer() # slow work stays outside the lock
return True
- The check and the act are now inside the same lock. No other thread can change the stock between them.
- The critical section is short. Other threads wait while one thread holds the lock. So do not put slow work inside it: network calls, file access, payments.
- If the payment fails, we must give the item back to the stock. This is one more reason to keep the reservation and the payment as clear, separate steps.
Use a lock for every read and write of the shared data. If one place forgets the lock, the protection is gone.
Deadlock: everyone waits forever
Locks fix races, but they bring a new danger. Imagine a transfer between two accounts, and each account has its own lock:
def transfer(src, dst, amount):
with src.lock:
with dst.lock:
src.balance -= amount
dst.balance += amount
- Thread 1 moves money from account A to account B. It takes the lock of A.
- At the same moment, thread 2 moves money from B to A. It takes the lock of B.
- Thread 1 now waits for the lock of B. Thread 2 waits for the lock of A.
- Nobody lets go. Both threads wait forever. This is a deadlock.
How to avoid it:
- Always take locks in the same order. For example, the account with the smaller id first. Then the circle cannot form.
- Use fewer locks. One lock for a small piece of data is often enough. Many small locks are faster on paper, but harder to get right.
- Use a timeout. The acquire method of a lock can take a timeout. If it fails, let go of everything, wait a little, and try again.
- Never call unknown code while holding a lock. That code may take another lock.
def transfer(src, dst, amount):
first, second = sorted([src, dst], key=lambda a: a.id)
with first.lock, second.lock:
src.balance -= amount
dst.balance += amount
Fix 2: when the app runs on many servers
In real life, the shop runs as several processes, often on several servers. Each process has its own memory, its own stock dictionary, and its own lock. A lock in memory protects only one process.
So the data must live in one shared place, like the database, and the change must be atomic there. The best way is to check and change in one statement:
def buy(conn, product_id: int) -> bool:
cur = conn.execute(
"UPDATE products SET stock = stock - 1 WHERE id = %s AND stock > 0",
(product_id,),
)
return cur.rowcount == 1 # 0 means sold out
- The database locks the row while it runs this one statement.
- The condition “stock above zero” and the change happen together. There is no gap between them.
- The second buyer changes zero rows, and gets “sold out”.
Another common way is optimistic concurrency. Every row has a version number. You update only if the version is still the one you read. If it changed, someone else won, and you read again and retry. Many ORMs support this.
The best lock is no shared data
The simplest way to avoid races is to not share data that can change.
- Immutable data. Data that never changes after it is created is safe to share. Create a new object instead of changing the old one.
- Each worker has its own data. For example, each thread counts in its own variable, and you add the results at the end.
- Send messages instead of sharing memory. One thread puts work into a queue. Worker threads take work from it. The queue.Queue class is already thread-safe.
import queue
import threading
orders = queue.Queue()
def worker():
while True:
order = orders.get()
process(order)
orders.task_done()
for _ in range(4):
threading.Thread(target=worker, daemon=True).start()
In code review and in interviews
When you see concurrent code, ask these questions:
- What data is shared? A global variable, a class field, a cache, a database row.
- Who writes it? If more than one thread or server writes it, it needs protection.
- Is there a gap between a check and an act? “If it exists, then create it” and “if there is stock, then take it” are classic examples.
- How many processes or servers run this code? If more than one, an in-memory lock is not enough.
- If there are two locks, are they always taken in the same order?
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| Changing shared data without a lock | Lost updates. Wrong numbers under load. | A lock, an atomic operation, or no shared data. |
| Check outside the lock, act inside it | The race is still there. | Put the check and the act in the same critical section. |
| Slow work inside a lock | All other threads wait. The app feels frozen. | Keep the critical section short. Do I/O outside. |
| Two locks taken in different orders | Deadlock. The service stops, the CPU is near zero. | One fixed order for all locks, or one lock. |
| An in-memory lock for an app on many servers | Each server has its own lock. The race is still there. | An atomic database update, or optimistic concurrency. |
| “Python has a GIL, so it is safe” | Races still happen between steps. | Protect shared data the same way as in any language. |
| Testing only with one user | The bug shows up first in production. | Load tests, and careful review of shared data. |
Summary in six lines
- Threads share memory. If two threads change the same data at the same time, updates can be lost.
- “Add one” and “check, then act” are not one step. Another thread can run in the gap.
- A lock makes a critical section run one thread at a time. Keep it short, and use it everywhere the data is touched.
- Two locks taken in different orders can cause a deadlock. Always take locks in one fixed order.
- With many processes or servers, an in-memory lock does not help. Use one atomic database statement or a version number.
- The best protection is no shared changing data: immutable objects, local data, or a queue.