Nâng CaoPython iconPython

Race condition là gì? Cách phòng tránh trong asyncio?

Race condition xảy ra khi nhiều coroutines đọc-modify-write shared state, kết quả phụ thuộc vào thứ tự thực thi.

Giải quyết bằng asyncio.Lock.

python
# Race condition
counter = 0
async def increment():
    global counter
    current = counter
    await asyncio.sleep(0)  # Yield — có thể bị preempt!
    counter = current + 1   # Ghi lại giá trị cũ

# Fix với Lock
lock = asyncio.Lock()
async def safe_increment():
    async with lock:
        global counter
        counter += 1  # Atomic trong lock context

Semaphore: giới hạn số coroutines concurrent. asyncio.Semaphore(10) tối đa 10 concurrent requests.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python