Atomic Versus Mutex Shared State
Guard a single counter with atomic.Int64 and protect cross-field invariants like budgets with a mutex, choosing the primitive that matches the workload.
Code
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)
}Following the data
Atomic Versus Mutex Shared State is built around the functions record, trySpend and main.
Repetition is confined to for i := 0; i < 8; i++ — the rest of the file is straight-line. The task is handed to a goroutine and runs concurrently. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
Signature: func (c *hitCounter) record()
Output lines are prefixed (hits:, used:), so each line points back to the step behind it.
Start the program and main runs record and trySpend one after another.
Key statements
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
Interactive Tools for This Topic
FAQ
- What does Atomic Versus Mutex Shared State print when run?
- The script runs standalone; its 2 labeled outputs include `hits:`, `used:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.