typestar

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

  1. atomic.Int64 has Add, Load, Store and CompareAndSwap.
  2. atomic.Value holds any single value atomically.
  3. Atomics suit counters and flags, not multi-field invariants.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 5 in Synchronization, step 18 of 25 in Concurrency.

← Previous Next →