Protect Shared State and Bound Resource Access
Core idea
An asyncio.Lock permits one holder at a time; it protects a critical section that might suspend. An asyncio.Semaphore(n) allows up to n simultaneous acquisitions when used correctly. Use async with to release on scope exit, including exceptions. Both primitives coordinate tasks on an event loop, not OS threads.
import asyncio
async def main(): lock=asyncio.Lock() state={'count':0} async def increment(): async with lock: old=state['count'] await asyncio.sleep(0) state['count']=old+1 await asyncio.gather(*(increment() for _ in range(4))) print(state['count'])
asyncio.run(main())The lock spans the read, suspension and write; no other holder overwrites the same old value.
Expected output:
4Verify two permits
import asyncio
async def main(): sem=asyncio.Semaphore(2) await sem.acquire() await sem.acquire() print(sem.locked()) sem.release() async with sem: print(sem.locked()) sem.release() print(sem.locked())
asyncio.run(main())locked means another acquisition would wait. The context releases its permit; the final release balances the first acquisition.
Expected output:
TrueTrueFalseCommon mistake
An asyncio.Lock is not reentrant; acquiring it again in the same task can deadlock. A semaphore is not a request-per-second rate limiter, and extra release calls on Semaphore can increase its counter.
Practice
Use a semaphore with capacity two for four independent jobs; keep a peak-active counter inside the protected region and assert it never exceeds two.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async locks and semaphores
Check your understanding of async locks and semaphores.
What is printed?
import asyncio
async def main(): lock=asyncio.Lock() async with lock: print(lock.locked()) print(lock.locked())
asyncio.run(main())What is printed?
import asyncio
async def main(): s=asyncio.Semaphore(1) async with s: print(s.locked())
asyncio.run(main())What should cover a suspending read-modify-write?
What does a semaphore bound?