Synchronization
What you will learn
- wait with
WaitGroupand protect invariants with mutexes; - choose between locks, atomics, and ownership;
- build a bounded worker-pool shape;
Channels are useful for communication. The sync package is useful when goroutines need to coordinate completion or safely share state.
Wait for work with WaitGroup
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Println("worker", id)
}(i)
}
wg.Wait()
Call Add before starting the goroutine. Each worker calls Done, normally with defer, and Wait blocks until the counter reaches zero.
A WaitGroup waits for completion; it does not collect errors or cancel sibling work.
Protect state with Mutex
type Counter struct {
mu sync.Mutex
value int
}
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.value++
}
func (c *Counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.value
}
Every access to protected fields—including reads—must follow the same locking rule.
Keep critical sections short. Do not hold a lock while performing slow network calls, waiting on channels, or calling unknown code unless the design specifically requires it.
RWMutex
sync.RWMutex allows several readers or one writer. It can help when reads are frequent, writes are rare, and the protected work is meaningful enough to justify the extra complexity.
Do not assume it is automatically faster than Mutex. Measure before optimising.
Run initialization once
var once sync.Once
func initialize() {
once.Do(func() {
fmt.Println("runs once")
})
}
sync.Once is useful for one-time initialisation shared by goroutines. If the function panics, that call still counts as having returned; future calls do not run it again.
Atomic operations
The sync/atomic package supports low-level operations on individual values. Atomics can be useful for counters or flags, but they do not automatically make a multi-step invariant safe.
Use a mutex when several fields or operations must change together. Clear code is more valuable than avoiding a small lock.
Do not copy synchronization values
Types such as Mutex and WaitGroup must not be copied after first use. Keep them as fields on a pointer-receiver struct and pass the struct by pointer when needed.
A worker-pool shape
func worker(jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
results <- job * job
}
}
A complete worker pool also needs clear ownership for closing channels, error handling, cancellation, and a bounded number of workers.
Practice
Build a safe in-memory counter used by 100 goroutines. Each goroutine should increment it 1,000 times. Wait for all work, print the result, and verify it is always 100000.
WaitGroup. Protect truly shared composite state with one mutex covering its complete invariant. Close results only after workers finish; atomics are appropriate only for simple independent values.Summary
WaitGroupwaits; it does not protect data.- A mutex must cover the entire shared invariant, not isolated field accesses.
- Bound worker counts and queues to bound resource use.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.