Back
+30 XP
Concept

Fix Race Conditions with Atomic Test-and-Set

Evaluating an object's state and modifying it in two separate Python bytecode operations invites race conditions under multi-threading. A thread context switch between the check and assignment lets multiple threads claim the same resource. Protect the read-modify-write cycle with locks.

python
import threading

class AtomicFlag:
    def __init__(self):
        self.flag = False
        self.lock = threading.Lock()
    def test_and_set(self):
        with self.lock:
            old = self.flag
            self.flag = True
            return old

# Fix Race Conditions with Atomic Test-and-Set Consider leader election or first-time initialization: ```python if not self.initialized: self.initialized = True self.launch_expensive_cluster() ``` If 10 threads arrive at the same millisecond, Thread 1 evaluates `if not self.initialized` (True). Right before it executes `self.initialized = True`, the operating system preempts Thread 1 and switches to Thread 2. Thread 2 also sees `False`, and both threads launch the expensive cluster! ⚡🛑 To prevent double-initialization or split-brain leaders, the test and the mutation must execute **atomically** as an indivisible unit using a mutex or hardware atomic primitive. ```python import threading class AtomicFlag: def __init__(self): self._lock = threading.Lock() self._state = False def test_and_set(self, new_val: bool) -> bool: with self._lock: prev = self._state self._state = new_val return prev ``` ## Pop Quiz Why does `if not claimed: claimed = True` fail under multi-threaded execution without synchronization? - [ ] Thread context switching can interrupt execution between reading claimed and updating it, allowing multiple threads inside. - [ ] Python booleans are immutable and thus allocate new memory addresses on every write. - [ ] The Python compiler turns sequential statements into speculative parallel branch predictions. - [ ] Thread memory caches do not synchronize without explicit os.sync() syscalls. ## Real-World Challenge Implement `AtomicFlag` with `test_and_set(new_state: bool) -> bool` and `compare_and_swap(expected: bool, new_val: bool) -> bool`. Verify that when 10 threads concurrently attempt to claim ownership via `test_and_set(True)`, exactly one thread receives `False` (the winning claim) and all others receive `True`. <details> <summary>Solution</summary> ```python import threading class AtomicFlag: def __init__(self, initial_state: bool = False): self._state = initial_state self._lock = threading.Lock() def test_and_set(self, new_state: bool) -> bool: with self._lock: old = self._state self._state = new_state return old def compare_and_swap(self, expected: bool, new_val: bool) -> bool: with self._lock: if self._state == expected: self._state = new_val return True return False @property def value(self) -> bool: with self._lock: return self._state # Verification flag = AtomicFlag(False) winners = [] def claim_slot(thread_id: int): # If old state was False, this thread successfully set it to True if not flag.test_and_set(True): winners.append(thread_id) threads = [threading.Thread(target=claim_slot, args=(i,)) for i in range(10)] for t in threads: t.start() for t in threads: t.join() assert len(winners) == 1, f"Expected exactly 1 winner, got {len(winners)}" assert flag.value is True # Test compare-and-swap assert flag.compare_and_swap(True, False) is True assert flag.value is False assert flag.compare_and_swap(True, True) is False # Fails because current is False ``` </details>