首次提交:初始化项目代码
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
// bulma/atomic_stress_test_demo.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var counter atomic.Uint64
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// 压力测试配置:10000个goroutine,每个累加1000次,总计1亿次操作
|
||||
goroutineNum := 10000
|
||||
perGoroutineOps := 1000
|
||||
wg.Add(goroutineNum)
|
||||
|
||||
start := time.Now()
|
||||
for i := 0; i < goroutineNum; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < perGoroutineOps; j++ {
|
||||
counter.Add(1) // 默认使用OrderSeqCst,安全稳定
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
cost := time.Since(start)
|
||||
expected := uint64(goroutineNum * perGoroutineOps)
|
||||
actual := counter.Load()
|
||||
|
||||
// 验证结果:判断实际计数与预期计数是否一致,验证原子操作稳定性
|
||||
fmt.Printf("压力测试完成:%d个goroutine,每个执行%d次累加\n", goroutineNum, perGoroutineOps)
|
||||
fmt.Printf("预期计数: %d\n", expected)
|
||||
fmt.Printf("实际计数: %d\n", actual)
|
||||
fmt.Printf("执行耗时: %v\n", cost)
|
||||
fmt.Printf("操作吞吐量: %.2f万次/毫秒\n", float64(expected)/float64(cost.Milliseconds()))
|
||||
|
||||
if actual == expected {
|
||||
fmt.Println("原子操作稳定可靠,无数据竞争!")
|
||||
} else {
|
||||
fmt.Printf("原子操作异常,计数偏差: %d\n", expected-actual)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user