Course contentsShow
← Python
Lesson 894 of 1,06014. Concurrency and PerformanceFree lesson

Synchronizing Coroutines with Asyncio Locks

Prevent race conditions when multiple coroutines access shared state by implementing asynchronous primitives for resource protection.

In this lesson, you will learn how to use asyncio.Lock to ensure that only one coroutine modifies a shared resource at any given time, preventing data corruption.

The Problem: Concurrent Interference

Even though asyncio runs on a single thread using an event loop, race conditions still occur. A coroutine can be suspended at any await expression. If two coroutines read a shared variable, perform an await (like a database call), and then update the variable, the state can become inconsistent because the second coroutine might have modified the data while the first was suspended.

Implementing Asynchronous Locks

To prevent this, we use asyncio.Lock. A lock acts as a gatekeeper: if a coroutine attempts to acquire a locked resource, it will wait until the current owner releases it.

Consider this shared bank balance scenario:

import asyncio

balance = 0
lock = asyncio.Lock()

async def update_balance(amount):
    global balance
    async with lock:
        # Critical section starts here
        temp = balance
        await asyncio.sleep(0.01)  # Simulate I/O latency
        balance = temp + amount
        # Critical section ends here

async def main():
    await asyncio.gather(update_balance(100), update_balance(-50))
    print(f"Final balance: {balance}")

asyncio.run(main())

In the code above, the async with lock: statement ensures that the block of code inside is executed atomically. Even if update_balance hits an await inside the block, the lock remains held. Any other coroutine trying to enter the async with lock block will pause until the first coroutine finishes and releases the lock.

Without the lock, both coroutines might read balance as 0, sleep, and then write their final result, causing one update to overwrite the other. By wrapping the "read-modify-write" cycle in a lock, you guarantee that each update is completed before the next one begins, preserving the integrity of your shared state.

Key Takeaway: Use asyncio.Lock as a context manager to define critical sections, ensuring that shared state remains consistent even when coroutines yield control via await.