33 lines
736 B
Go
33 lines
736 B
Go
// bulma/atomic_memory_order.go
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
var relaxedCounter atomic.Uint64 // 无符号原子计数器
|
|
var wg sync.WaitGroup
|
|
|
|
// 使用 Relaxed 顺序(仅保证原子性,无全局顺序约束)
|
|
start := time.Now()
|
|
for i := 0; i < 100; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
for j := 0; j < 10000; j++ {
|
|
// 第二个参数指定内存顺序:OrderRelaxed(无顺序约束,仅保证原子性)
|
|
relaxedCounter.Add(1)
|
|
}
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
fmt.Printf("✅ Relaxed 计数: %d (耗时: %v)\n",
|
|
relaxedCounter.Load(),
|
|
time.Since(start))
|
|
// 注意:最终值正确,但中间状态可能"乱序"被其他 goroutine 观察到
|
|
}
|