package main import ( "fmt" "sync" "sync/atomic" ) func main() { var counter int64 var wg sync.WaitGroup const goroutines, increments = 10, 10000 wg.Add(goroutines) for i := 0; i < goroutines; i++ { go func() { defer wg.Done() for j := 0; j < increments; j++ { for { old := atomic.LoadInt64(&counter) if atomic.CompareAndSwapInt64(&counter, old, old+1) { break // 成功则退出重试循环 } // 失败:其他 goroutine 已修改,重试 } } }() } wg.Wait() fmt.Printf("✅ 最终计数值: %d (期望: %d)\n", counter, goroutines*increments) }