typestar

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

  1. atomic.Int64 updates safely without a mutex.
  2. Add and Load are single atomic operations.
  3. sync.Once runs its setup exactly once across goroutines.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Synchronization, step 17 of 25 in Concurrency.

← Previous Next →