Python
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.
Exercise 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())).
Show example solution
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()))
Test yourself
-
What does the async with lock: block provide?
- Only one coroutine can be inside
- No coroutine can enter
- It acquires the lock permanently
- Many coroutines can enter at once
Show answer
Only one coroutine can be inside — async with lock allows one coroutine at a time; the lock releases when the block ends.
-
Define a Lock
import asyncio
lock = asyncio.____()
Show answer
import asyncio
lock = asyncio.Lock()
-
Match the Lock concepts
- asyncio.Lock()
- Lock object
- async with lock
- Critical section
- shared += 1
- Shared update
- waiting coroutine
- Waits in queue
Next lesson: Semaphore