Atomic types in Go
The typed atomics carry their own memory, so a mutex is unnecessary.
type Stats struct {
requests atomic.Int64
failures atomic.Int64
stopped atomic.Bool
}
func (s *Stats) Record(ok bool) {
s.requests.Add(1)
if !ok {
s.failures.Add(1)
}
}
func (s *Stats) Report() string {
return fmt.Sprintf("%d/%d failed, stopped=%t",
s.failures.Load(), s.requests.Load(), s.stopped.Load())
}
How it works
atomic.Int64has Add, Load, Store and CompareAndSwap.atomic.Valueholds any single value atomically.- Atomics suit counters and flags, not multi-field invariants.
Keywords and builtins used here
boolfuncifreturnstringstructtype
The run, in numbers
- Lines
- 17
- Characters to type
- 310
- Tokens
- 94
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 54 seconds.
Step 5 of 5 in Synchronization, step 18 of 25 in Concurrency.