Avoid copying synchronization objects
Avoid copying synchronization objects
A struct assignment copies its fields, including embedded lock state. Mutex, RWMutex, WaitGroup, Once, Cond, Map, Pool and typed atomic values must not be copied after first use. Pass pointers to lock-bearing structs and use pointer receivers.
package main
import ( "fmt" "sync")
type Meter struct { mu sync.Mutex n int}
func (m *Meter) Add() { m.mu.Lock(); defer m.mu.Unlock(); m.n++ }func (m *Meter) Value() int { m.mu.Lock(); defer m.mu.Unlock(); return m.n }func record(m *Meter) { m.Add() }func main() { m := new(Meter) record(m) record(m) fmt.Println(m.Value())}Copying a pointer preserves object identity. A value receiver instead copies the struct. Even a copied unlocked mutex does not coordinate with the original. go vet can detect many accidental copies using copylocks; a clean report is not proof of correct ownership.
Expected output:
2Return independent snapshots
package main
import ( "fmt" "sync")
type Store struct { mu sync.Mutex items []string}
func (s *Store) Snapshot() []string { s.mu.Lock() defer s.mu.Unlock() return append([]string(nil), s.items...)}func main() { s := &Store{items: []string{"a", "b"}} view := s.Snapshot() view[0] = "x" fmt.Println(s.Snapshot(), view)}The method returns copied data rather than the lock or original backing array. Strings are immutable; pointer-bearing elements may require deeper copying. Avoid growing slices of already-used lock-bearing structs by value. A slice of pointers keeps identities stable.
Expected output:
[a b] [x b]Try it locally
Create two pointer-owned counters, increment each through a pointer receiver and print 1 1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 08: Avoid copying synchronization objects
Check the lesson objective before moving on.
What is copied when passing *Meter?
What should a snapshot return?