InterviewHubPRO
Section Overview
Q34

Question 34 of 65

Part 3: Asynchronous Programming & Concurrency (26 - 40)

52%
Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)

Race Conditions and Locks:

In Simple Words: A race condition occurs when two threads concurrently read and modify shared data. Fix: Protect critical sections using threading.Lock or asyncio.Lock.

python
# AsyncIO Lock protecting shared in-memory balance:
balance = 100
lock = asyncio.Lock()

async def withdraw(amount):
    global balance
    async with lock:
        if balance >= amount:
            await asyncio.sleep(0.01) # Context switch
            balance -= amount
            return True
        return False