实现说明
atomic 与 mutex 的取舍可以归结为函数 record、trySpend、main。
驱动整个流程的是 for i := 0; i < 8; i++ 这一个循环。goroutine 把工作从当前执行流上接走。清理逻辑用 defer 挂载,函数的任何退出路径都会执行。
使用要点
- 整个依赖故事就是语言版本本身。
- 跑完文件,输出里会留下标记——
hits:、used:。 main按顺序串起record、trySpend;运行文件就会把这个流程跑一遍。
常见问题
运行「atomic 与 mutex 的取舍」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 hits:、used: 标签标明各步骤。
主签名形如 func (c *hitCounter) record()
核心语句
func (b *budget) trySpend(cents int64) bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.usedCents+cents > b.limit {
return false // 拒绝但两个不变量字段保持一致
}
b.usedCents += cents
return true
}
func (c *hitCounter) record() {
c.total.Add(1)
}
var wg sync.WaitGroup
代码示例
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// 场景一:单个独立计数器 —— atomic 足够,无锁竞争更小
type hitCounter struct {
total atomic.Int64
}
func (c *hitCounter) record() {
c.total.Add(1)
}
// 场景二:used 与 limit 必须一起判定 —— 不变量跨字段,需要 mutex
type budget struct {
mu sync.Mutex
usedCents int64
limit int64
}
func (b *budget) trySpend(cents int64) bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.usedCents+cents > b.limit {
return false // 拒绝但两个不变量字段保持一致
}
b.usedCents += cents
return true
}
func main() {
var hits hitCounter
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
hits.record()
}
}()
}
wg.Wait()
fmt.Println("hits:", hits.total.Load())
b := &budget{limit: 1000}
fmt.Println(b.trySpend(600), b.trySpend(500), b.trySpend(400))
fmt.Println("used:", b.usedCents, "of", b.limit)
}