talira

atomic (Go)

Typed wrappers around Go sync/atomic that enforce atomic access

open sourceMITfree

atomic is a Go library from Uber that wraps primitive types (integers, booleans, floats, strings, durations, times, errors, pointers) in types whose only methods are atomic, so a variable meant for atomic access can never be read or written plainly by mistake. It keeps everything the standard library sync/atomic offers, including CompareAndSwap, behind a more convenient API. Its import path is go.uber.org/atomic; the old github.com/uber-go/atomic path stopped compiling with Go modules at v1.5.0. Install it with go get go.uber.org/atomic@v1.

Problems it solves

  • stop teammates from reading a shared counter without sync/atomic in a Go service
  • atomic booleans and durations in Go without remembering which variables need atomic calls
  • share a flag between goroutines in Go with a type that only allows atomic loads and stores

Features

  • typed atomic integers, booleans, floats, strings, durations and times
  • generic atomic Pointer[T]
  • CompareAndSwap, Swap, Add and Sub methods
  • JSON marshalling for atomic types

Limitations

  • The legacy import path github.com/uber-go/atomic doesn't compile with Go modules from v1.5.0; old dependencies need a replace directive.1