Mutexes Cheatsheet

Standard Mutex (sync.Mutex)

  • Use: Exclusive access (one worker at a time).
  • Methods: mu.Lock(), mu.Unlock().
  • Pattern:
mu.Lock()
defer mu.Unlock()

Read-Write Mutex (sync.RWMutex)

  • Use: High-read workloads. Allows many readers but only one writer.
  • Write Methods: mu.Lock(), mu.Unlock().
  • Read Methods: mu.RLock(), mu.RUnlock().

Common Gotchas

  • Maps: NOT thread-safe. Always protect with a mutex if concurrent access is possible.
  • Deadlocks: Occur if you forget to Unlock() or if a goroutine tries to Lock() a mutex it already holds.
  • Copies: Never copy a mutex. If a struct contains a mutex, pass that struct by pointer.

Key Terminology

  • Mutual Exclusion: The act of excluding others from accessing a resource.
  • Critical Section: The part of the code protected by a lock.
  • Race Condition: Unpredictable behavior caused by unsynchronized concurrent access.