package main import ( "fmt" "sync" ) const ( goroutines = 10 addsPerG = 100 ) func main() { var ( counter int mu sync.Mutex wg sync.WaitGroup ) wg.Add(goroutines) for i := 0; i < goroutines; i++ { go func() { defer wg.Done() for j := 0; j < addsPerG; j++ { mu.Lock() // 进入临界区 counter++ mu.Unlock() // 离开临界区 } }() } wg.Wait() fmt.Println("final counter:", counter) }