Resource Sharing & Critical Sections (Deep Dive)
1. The “Why” In multithreading, a Critical Section is any segment of code that accesses a shared resource (like a variable, a file, or a database connection) where at least one thread is performing a write operation. The problem is that most high-level operations (like count++) are not atomic. To the CPU, count++ is actually three distinct steps: Load: Move the value from the Main Memory (Heap) into a CPU Register. Increment: Add 1 to the value inside the Register. Store: Move the new value from the Register back to Main Memory. If Thread A is “paused” (context-switched) after Step 2, and Thread B performs all three steps, Thread A will eventually wake up and overwrite Thread B’s work with an outdated value. This is a Race Condition. ...