Atomics and sync.Once in Go
Lock-free counters, and one-time initialization.
var (
hits atomic.Int64
setupOnce sync.Once
)
func record() int64 {
setupOnce.Do(func() {
hits.Store(0)
})
return hits.Add(1)
}
func snapshot() int64 {
return hits.Load()
}
How it works
atomic.Int64updates safely without a mutex.AddandLoadare single atomic operations.sync.Onceruns its setup exactly once across goroutines.
Keywords and builtins used here
funcint64returnvar
The run, in numbers
- Lines
- 15
- Characters to type
- 179
- Tokens
- 54
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 31 seconds.
Step 4 of 5 in Synchronization, step 17 of 25 in Concurrency.