The before code reads and updates availability without any protection, so two requests can read the same available count and both book, causing double booking. The after code uses a lock to ensure only one thread updates availability at a time, preventing conflicts.
### Before: No concurrency control, leads to double booking
class BookingService:
def book_slot(self, slot_id):
slot = database.get_slot(slot_id)
if slot.available > 0:
slot.available -= 1
database.save_slot(slot)
return True
return False
### After: Using a lock to prevent concurrent updates
import threading
lock = threading.Lock()
class BookingService:
def book_slot(self, slot_id):
with lock:
slot = database.get_slot(slot_id)
if slot.available > 0:
slot.available -= 1
database.save_slot(slot)
return True
return False