Understanding Critical Sections
Think Of It Like A Bathroom
A critical section is like a single-occupancy bathroom. One person goes in, locks the door, does their business, and unlocks when done. While locked, others must wait. The lock ensures privacy and prevents awkward collisions.
The Four Requirements
Mutual exclusion: Only one thread in the critical section at a time. This is the fundamental requirement.
Progress: If no thread is in the critical section and some want to enter, one must be allowed in. No indefinite postponement.
Bounded waiting: A thread cannot wait forever. There must be a limit on how many times others can enter before you.
No assumptions: The solution must not depend on CPU speed or number of processors.
Keep It Short
Critical sections should be as small as possible. Long critical sections block other threads, reducing parallelism. Only protect what absolutely needs protection.