Lock Semantics and Acquire/Release
What You'll Learn
You'll learn how the two fundamental lock operations—acquire and release—work together to enforce mutual exclusion in critical sections.
The Core Idea
A lock is a synchronization primitive that controls access to shared resources. It has two essential operations:
-
acquire(lock)(also calledlock()): Attempts to gain exclusive access. If another thread already holds the lock, the calling thread blocks (waits) until the lock becomes available. Once acquired, the thread proceeds with exclusive access. -
release(lock)(also calledunlock()): Relinquishes ownership of the lock, allowing other waiting threads to acquire it.
How It Solves Mutual Exclusion
Locks ensure that only one thread can be inside a critical section at a time:
acquire(lock)
// Critical section - only one thread here at a time
// Access shared resource safely
release(lock)
When Thread A calls acquire(), it gets the lock and enters the critical section. If Thread B then calls acquire() on the same lock, it blocks and waits. Only when Thread A calls release() does Thread B wake up, acquire the lock, and proceed.
The Waiting Room Analogy
Think of a single-occupancy restroom with a lock. Acquire means trying to lock the door—if it's already locked, you wait outside. Release means unlocking and leaving—the next person waiting can now enter and lock it behind them.
Why This Matters
These simple semantics—block until available, then release when done—are the foundation for protecting critical sections. The acquire/release pattern guarantees mutual exclusion, preventing race conditions on shared data.
Key Takeaway: acquire() blocks until exclusive access is granted; release() frees the lock for others—together they enforce one-at-a-time access to critical sections.