Prevent overlapping access to a critical section.
Section: Synchronization Primitives
Protect shared state with a Lock
python
python
import asyncio
counter = 0
lock = asyncio.Lock()
async def increment():
global counter
async with lock:
current = counter
await asyncio.sleep(0)
counter = current + 1
async def main():
await asyncio.gather(*(increment() for _ in range(100)))
print(counter)
asyncio.run(main())Explanation
Use `asyncio.Lock()` when multiple tasks mutate shared state.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Synchronization Primitives
Signal readiness with an Event
Wake waiting tasks once a condition becomes true.
Limit concurrency with a Semaphore
Throttle parallel access to a finite resource.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.