Middle+
Can a race condition occur in asynchronous Python code?
sobes.tech AI
Answer from AI
Yes, a race condition can occur in asynchronous Python code, especially if multiple coroutines or tasks access and modify shared data simultaneously without proper synchronization.
Although Python uses GIL (Global Interpreter Lock), which prevents true parallel execution of bytecode in multiple threads, in asynchronous code, multiple tasks can switch at arbitrary points, leading to race conditions when accessing shared resources.
Example:
import asyncio
shared_counter = 0
async def increment():
global shared_counter
temp = shared_counter
await asyncio.sleep(0) # context switch
shared_counter = temp + 1
async def main():
tasks = [increment() for _ in range(1000)]
await asyncio.gather(*tasks)
print(shared_counter)
asyncio.run(main())
In this example, due to context switching between reading and writing shared_counter, the final value can be less than 1000, indicating a race condition.
To prevent such issues, synchronization mechanisms like asyncio.Lock are used.