// Chapter 38 example: the same counter, guarded by a sync.Mutex. The total is // right on every run. // Run with: go run exercises/38/02-mutex-counter.go package main import ( "fmt" "sync" ) func main() { // mu protects count. Any code that reads or changes count must hold mu. var mu sync.Mutex count := 0 var wg sync.WaitGroup for range 10 { wg.Go(func() { for range 100000 { mu.Lock() count = count + 1 mu.Unlock() } }) } wg.Wait() fmt.Println("Expected: 1000000") fmt.Println("Got: ", count) }