🐹 Go (Golang) Intermediate

What is sync.Mutex and when do you use it?

Answer

sync.Mutex is a mutual exclusion lock that protects shared data from concurrent access by multiple goroutines. Call mu.Lock() before accessing shared state and mu.Unlock() after — typically with defer mu.Unlock() immediately after locking to ensure it releases even if the function panics. Use sync.RWMutex when reads are far more frequent than writes — RLock()/RUnlock() allows multiple concurrent readers while still providing exclusive write access. The race detector (go test -race) catches Mutex misuse in tests.