CodeBlanks Logo Icon CodeBlanks

Lock

Learn critical sections with asyncio.Lock.

Lock

asyncio.Lock protects a critical section. Only one coroutine holds the lock at a time; others wait. This serializes access to shared state.

lock = asyncio.Lock()

async with lock:
    # critical section
    shared += 1

The async with lock: block acquires the lock; it auto-releases when the block ends. Multiple coroutines cannot enter this block at once; waiters are queued.

Lock is used when a resource needs exclusive access; for example writing to a file or updating a counter.

Critical section and sharing

If multiple coroutines update the same variable, intermediate values can mix. async with lock: makes the update atomic; one coroutine finishes before another enters.

Example: shared += 1 is actually read-increment-write. If an await happens between these steps, another coroutine can interleave. Lock turns these steps into one atomic unit.

But overuse of Lock reduces concurrency; use it only where truly needed.

Practice Protected counter with Lock

Start with import asyncio. Define shared = 0 and lock = asyncio.Lock() at module level. The function async def inc() starts with global shared, then inside async with lock: does shared += 1. Inside async def main() call await asyncio.gather(inc(), inc()); then return shared. Add print(asyncio.run(main())).

Starter code

main.py
# import the asyncio module
# define a global variable shared (start at 0)
# define a lock object with asyncio.Lock
# inc(): inside async with lock, increment shared by 1
# main: gather two inc calls, then return shared; print result

Sample solution

main.py
import asyncio

shared = 0
lock = asyncio.Lock()

async def inc():
    global shared
    async with lock:
        shared += 1

async def main():
    await asyncio.gather(inc(), inc())
    return shared

print(asyncio.run(main()))

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the async with lock: block provide?

  • Only one coroutine can be inside Correct answer
  • No coroutine can enter
  • It acquires the lock permanently
  • Many coroutines can enter at once

Explanation: async with lock allows one coroutine at a time; the lock releases when the block ends.

2 Define a Lock

Question
import asyncio

lock = asyncio.____()
Answer
import asyncio

lock = asyncio.Lock()

Explanation: asyncio.Lock() creates a new lock.

3 Match the Lock concepts

Term Meaning
asyncio.Lock() Lock object
async with lock Critical section
shared += 1 Shared update
waiting coroutine Waits in queue

All lessons in Advanced