Mutex
ELI5 - The Vibe Check
A mutex is a single key to a single bathroom. Only one thread can hold the key at a time, so only one thread can be inside the critical section of code touching some shared piece of data. Everyone else waits in line outside the door until the key gets handed back.
Real Talk
A mutex (mutual exclusion lock) is a synchronization primitive that allows only one thread to hold it at a time, used to protect a critical section of code that accesses shared, mutable state. Threads that attempt to acquire an already-held mutex block until it is released, which prevents data races but can introduce contention and, if used carelessly across multiple locks, deadlock.
Show Me The Code
mu.Lock()
defer mu.Unlock()
counter++ // safe: only one goroutine at a time
When You'll Hear This
"Wrap that shared map access in a mutex before two goroutines corrupt it." / "We're seeing lock contention because everything funnels through one giant mutex."
Related Terms
Data Race
A data race is what happens when two threads touch the exact same piece of memory at the exact same time, and at least one of them is writing, with nothing...
Deadlock
A deadlock is when two things are each waiting for the other to go first, and neither ever does. Thread A holds Lock 1 and wants Lock 2.
Lock Contention
Lock contention is what happens when a mutex becomes the most popular door in the building, and instead of doing useful work, half your threads are just st...
Lock-Free
Lock-free code gets multiple threads to safely share data without ever making anyone stand in line waiting for a lock.