Junior — Middle
Can you give an example of a race condition in the asyncio asynchronous library?
sobes.tech AI
Answer from AI
Race condition in asyncio occurs when multiple coroutines try to modify a shared resource simultaneously without proper synchronization.
Example:
import asyncio
counter = 0
async def increment():
global counter
temp = counter
await asyncio.sleep(0.1) # simulate delay
counter = temp + 1
async def main():
await asyncio.gather(increment(), increment())
print(f'Counter: {counter}')
asyncio.run(main())
Expected result: Counter: 2, but due to race conditions, it might be Counter: 1, as both coroutines read the same value of counter before updating.
To prevent race conditions, synchronization is used, for example, asyncio.Lock:
lock = asyncio.Lock()
async def safe_increment():
global counter
async with lock:
temp = counter
await asyncio.sleep(0.1)
counter = temp + 1
async def main():
await asyncio.gather(safe_increment(), safe_increment())
print(f'Counter: {counter}')
asyncio.run(main())
Now, counter will correctly increase to 2, as access to the resource is protected.