Race Conditions: When Shared State Collapses
A race condition occurs when multiple threads read and write shared data without synchronization. The final outcome depends unpredictably on OS thread scheduling 💥.
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
counter += 1 # Not atomic! Read, increment, store 💥
threads = [threading.Thread(target=increment) for _ in range(2)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Counter: {counter}") # Often less than 200,000!
# 51. Race Conditions: When Shared State Collapses A race condition occurs when multiple threads read and write shared data without synchronization. The final outcome depends unpredictably on OS thread scheduling 💥. ```python import threading counter = 0 def increment(): global counter for _ in range(100000): counter += 1 # Not atomic! Read, increment, store 💥 threads = [threading.Thread(target=increment) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() print(f"Counter: {counter}") # Often less than 200,000! ``` Even `counter += 1` consists of three separate Python bytecode instructions (`LOAD_GLOBAL`, `BINARY_OP`, `STORE_GLOBAL`). A thread switch mid-operation corrupts state! 💥 --- ### Question Why is `counter += 1` not safe to execute across multiple threads simultaneously? 🧠- [ ] a. It decomposes into multiple bytecode instructions where threads can interleave 💥 - [ ] b. Python automatically resets integers to 0 during thread swaps - [ ] c. CPython converts addition into string concatenation when threads run - [ ] d. The Linux kernel blocks arithmetic operations on non-main threads --- ### Challenge Write a function `safe_or_unsafe(is_locked)` that returns `'Atomic'` if `is_locked` is True else `'Race Condition'`. Print `safe_or_unsafe(True)` and `safe_or_unsafe(False)`. 🎯 <details> <summary>Solution</summary> ```python def safe_or_unsafe(is_locked): return "Atomic" if is_locked else "Race Condition" print(safe_or_unsafe(True)) print(safe_or_unsafe(False)) ``` </details>