Type-safe atomic operations for Go primitive types. This package provides convenient wrappers around Go's sync/atomic package to ensure safe concurrent access to shared variables.
go get next.orly.dev/pkg/utils/atomic
The atomic package provides type-safe wrappers around Go's standard sync/atomic operations:
import "next.orly.dev/pkg/utils/atomic"
// Integer types
var counter atomic.Uint64
counter.Store(42)
value := counter.Load() // 42
counter.Add(8) // 50
// Boolean operations
var flag atomic.Bool
flag.Store(true)
if flag.Load() {
// Handle true case
}
// Pointer operations
var ptr atomic.Pointer[string]
ptr.Store(&someString)
loadedPtr := ptr.Load()
// Compare and swap
var value atomic.Int64
value.Store(100)
swapped := value.CompareAndSwap(100, 200) // true, value is now 200
// Swap operations
oldValue := value.Swap(300) // oldValue = 200, new value = 300
// Atomic add/subtract
delta := value.Add(50) // Add 50, return new value (350)
value.Sub(25) // Subtract 25, value is now 325
| Type | Description |
|---|---|
Bool | Atomic boolean operations |
Int32 | 32-bit signed integer |
Int64 | 64-bit signed integer |
Uint32 | 32-bit unsigned integer |
Uint64 | 64-bit unsigned integer |
Uintptr | Pointer-sized unsigned integer |
Float64 | 64-bit floating point |
Pointer[T] | Generic pointer type |
// Type-safe pointer operations
var config atomic.Pointer[Config]
config.Store(&myConfig)
// Load with type safety
currentConfig := config.Load()
if currentConfig != nil {
// Use config with full type safety
}
All atomic types implement a consistent interface:
Load() T - Atomically load the current valueStore(val T) - Atomically store a new valueSwap(new T) T - Atomically swap values, return old valueCompareAndSwap(old, new T) bool - CAS operationAdditional methods by type:
Integer Types (Int32, Int64, Uint32, Uint64):
Add(delta T) T - Atomically add delta, return new valueSub(delta T) T - Atomically subtract delta, return new valueFloat64:
Add(delta float64) float64 - Atomically add deltaThe atomic package includes comprehensive tests:
# Run atomic package tests
go test ./pkg/utils/atomic
# Run with verbose output
go test -v ./pkg/utils/atomic
# Run with race detection
go test -race ./pkg/utils/atomic
# Run with coverage
go test -cover ./pkg/utils/atomic
Part of the full test suite:
# Run all tests including atomic
./scripts/test.sh
# Run specific package tests
go test ./pkg/utils/...
Tests cover:
The atomic wrappers have zero runtime overhead compared to direct sync/atomic calls. The Go compiler inlines all wrapper methods, resulting in identical generated code.
go build ./pkg/utils/atomic
See the test files for comprehensive usage examples and edge cases.
Part of the next.orly.dev project. See main LICENSE file.