Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 40 ยท Synchronization and Queues

Locks and Race Conditions in asyncio

Learn when asyncio code has race conditions despite one thread, how an await between read and write breaks data, and how asyncio.Lock fixes it safely.

Because asyncio runs on one thread, many people believe race conditions cannot happen. They can. The loop switches tasks at every await, so any state that is shared between tasks and modified across an await can be corrupted. In this lesson you will build a real race on purpose, see it lose data, and fix it with asyncio.Lock.

What is safe and what is not

Between two awaits, your code runs without interruption. These are safe from other tasks:

Python
counter += 1                  # no await inside: runs as one uninterrupted step

But this pattern is not safe:

Python
current = balance             # read
await something_slow()        # other tasks run here and may change balance
balance = current + 100       # write based on a stale value

The danger is a read, await, write sequence on shared data. While your task waits, another task reads the same old value and writes its own result, and one of the two updates is lost.

A race condition you can run

Ten tasks each add 100 to a shared account balance. Each one reads the balance, "talks to the bank" (an await), then writes the new value. The correct final balance is 1,000:

Python Losing updates without a lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All ten tasks read balance as 0 before any of them wrote, so the last write wins and the final balance is 100. Nine deposits vanished. This is a classic lost update.

sequenceDiagram
    participant A as Task A
    participant B as Task B
    participant S as balance
    A->>S: read 0
    B->>S: read 0
    A->>S: write 100
    B->>S: write 100 (lost A's update)

Both tasks read the same old value, so the second write overwrites the first.

The fix: asyncio.Lock

A lock lets only one task at a time enter a critical section. Other tasks that try to enter wait (without blocking the loop) until it is released. Use it as an async context manager:

Python Fixing it with asyncio.Lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Now the result is 1,000. The tasks queue up at the lock and take turns, so the read, the await and the write form one atomic unit. The price is that the critical sections run one after another (this example takes about 0.1 seconds, not 0.01), so keep them as short as possible and never hold a lock across long, unrelated work.

Using the lock

Operation Meaning
async with lock: acquire, run the block, always release (recommended)
await lock.acquire() / lock.release() manual control; pair them with try/finally
lock.locked() is it currently held?

The lock is fair: waiting tasks acquire it in first-in, first-out order. It is not reentrant: if a task that already holds the lock tries to acquire it again, it waits for itself forever (a deadlock).

Python Observing the lock queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A takes the free lock at once, so it is inside before B and C even print their messages. B and C then see locked=True and wait, and they enter in the order they asked: B, then C. Only the inside section is serialized.

Deadlocks

Two classic ways to hang forever:

  1. Re-acquiring a held lock in the same task (not reentrant).
  2. Lock ordering: task 1 holds lock X and waits for lock Y; task 2 holds Y and waits for X. Fix by always acquiring multiple locks in the same global order.

When a program "just stops", check what tasks are awaiting. Python 3.14 offers python -m asyncio ps PID and pstree to inspect running tasks, and asyncio.all_tasks() lists them from inside.

Can you avoid locks altogether?

Often yes, and that is better. Options:

  • Make the update atomic by not awaiting in the middle. balance += amount with no await in between needs no lock.
  • Do the await first, then update. Fetch the data, then apply it in a single step with no await between reading and writing.
  • Own the data in one task. Let one task manage the state and let others send it messages through a queue. This "actor" style removes the shared state completely.
Python Avoiding the race by not awaiting mid-update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This version is correct without a lock, because no other task can run between reading and writing balance. Use a lock when the update must span an await.

Locks are tied to the event loop

An asyncio.Lock is not thread-safe and not process-safe. It protects tasks on one loop only. To protect data shared with other threads use threading.Lock; for several processes use inter-process tools.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which code is vulnerable to a race condition in asyncio?

    Other tasks can run during the await and change the shared value, so the later write uses stale data.
  2. 2. What does async with lock: guarantee?

    The lock serializes access to the critical section and always releases, even on errors.
  3. 3. A task holding an asyncio.Lock tries to acquire the same lock again. What happens?

    asyncio.Lock is not reentrant, so the second acquire waits for a release that never comes.
  4. 4. How can you avoid needing a lock for a counter update?

    Without an await in between, no other task can interleave, so the update is already atomic.

Summary

  • One thread does not prevent races: an await between read and write lets other tasks change the data.
  • asyncio.Lock with async with protects a critical section; waiters queue up fairly.
  • Keep critical sections short; the lock is not reentrant, and inconsistent lock ordering deadlocks.
  • Prefer designs without shared mutable state: no await mid-update, or one owner task plus a queue.

Next: Events and conditions