Asyncio Shield Critical Section
Protect critical sections from cancellation with asyncio.shield for atomic operations.
Code
import asyncio
async def critical_operation():
await asyncio.sleep(2)
return 'done'
async def handler():
try:
result = await asyncio.shield(critical_operation())
return result
except asyncio.CancelledError:
print('handler cancelled, critical still running')
raise
async def main():
task = asyncio.create_task(handler())
await asyncio.sleep(0.5)
task.cancel()
try:
await task
except asyncio.CancelledError:
passReport a problem with this exampleOpens a pre-filled issue on GitHub.