Skip to content

15 — Locks

rebeloper edited this page Jul 12, 2026 · 1 revision

🍽️ Intuition

A single ticket pad on the counter — only one chef may hold the pen at a time, everyone else waits their turn to write.

🧠 What It Means In Swift

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).

📊 ASCII Diagram

Chef A ──▶ [🖊️ pen] ──▶ writes ──▶ passes pen
Chef B ──▶ waits for pen ──▶ [🖊️ pen] ──▶ writes

💻 Tiny Swift Example

let lock = NSLock()
var counter = 0

func increment() {
    lock.lock()
    counter += 1
    lock.unlock()
}

🔄 vs. Swift Concurrency

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.

🧸 Memory Sentence

A lock is the one pen on the counter — only one chef writes at a time.

⚠️ Analogy Limit

Forgetting to "put the pen back" (unlock()) in real life just annoys the next chef; forgetting unlock() in code deadlocks every future caller.

✅ Check Your Understanding

What happens if lock() is called twice in a row on the same NSLock without an unlock() in between?

Clone this wiki locally