-
Notifications
You must be signed in to change notification settings - Fork 0
15 — Locks
A single ticket pad on the counter — only one chef may hold the pen at a time, everyone else waits their turn to write.
Locks provide manual mutual exclusion around shared state. NSLock is a simple, general-purpose lock; os_unfair_lock is a lower-level, lighter-weight primitive with less overhead but stricter usage rules (it must be unlocked from the same thread that locked it).
Chef A ──▶ [🖊️ pen] ──▶ writes ──▶ passes pen
Chef B ──▶ waits for pen ──▶ [🖊️ pen] ──▶ writes
let lock = NSLock()
var counter = 0
func increment() {
lock.lock()
counter += 1
lock.unlock()
}Actors replace manual locks with compiler-enforced isolation — you never call .lock()/.unlock() yourself, the compiler guarantees only one task touches actor state at a time.
A lock is the one pen on the counter — only one chef writes at a time.
Forgetting to "put the pen back" (unlock()) in real life just annoys the next chef; forgetting unlock() in code deadlocks every future caller.
What happens if lock() is called twice in a row on the same NSLock without an unlock() in between?