Protect shared state with Mutex
Protect shared state with Mutex
A mutex gives one goroutine at a time access to a critical section. Protect every access to the same mutable state with the same lock, not just writes. A zero-value sync.Mutex is ready to use. Lock before reading or changing a shared counter; Unlock when the operation is complete.
package main
import ( "fmt" "sync")
func main() { var mu sync.Mutex var wg sync.WaitGroup n := 0 for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done(); mu.Lock(); n++; mu.Unlock() }() } wg.Wait() fmt.Println(n)}Increment is a read-modify-write operation. Lock covers the entire operation. WaitGroup joins the workers before main reads n; it does not protect concurrent increments. Unlock synchronizes before a later successful Lock on the same mutex. A mutex is not reentrant: acquiring it twice without releasing it can block forever.
Expected output:
4Keep lock ownership in methods
package main
import ( "fmt" "sync")
type Counter struct { mu sync.Mutex n int}
func (c *Counter) Add(n int) { c.mu.Lock(); defer c.mu.Unlock(); c.n += n }func (c *Counter) Value() int { c.mu.Lock(); defer c.mu.Unlock(); return c.n }func main() { var c Counter c.Add(3) c.Add(4) fmt.Println(c.Value())}Pointer receivers share the same lock. Defer releases it on every return path, including ordinary panic unwinding. Keep critical sections short; avoid calling unknown callbacks or blocking on I/O while holding a lock. Do not copy the Counter after use.
Expected output:
7Try it locally
Launch three goroutines adding 2 to one protected counter; join and print 6.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 01: Protect shared state with Mutex
Check the lesson objective before moving on.
What must the lock cover?
What does WaitGroup alone protect?