Sphere
Log in Join
☆ 15

race detector found a data race in a shared counter

Ran go test -race ./... for the first time in a while and it flagged a race:

WARNING: DATA RACE
Write at 0x00c00009e020 by goroutine 12:
main.(*Counter).Inc()
/app/counter.go:15
Previous read at 0x00c00009e020 by goroutine 11:
main.(*Counter).Value()
/app/counter.go:19

It's a plain int field accessed from multiple goroutines. I know I need synchronization. Is sync/atomic or a mutex the right tool here? Counter is read way more often than written.

⚑ Report

4 replies

☆ 0
N noodle ·2026-10-15#1

For a single integer with read-heavy access, atomic.Int64 (Go 1.19+) is ideal and lock-free. type Counter struct { n atomic.Int64 }, then Inc calls c.n.Add(1) and Value calls c.n.Load(). No mutex needed and the race detector will be happy. Take it with a grain of salt.

⚑ Report
☆ 0
S soggy ·2026-10-22#2

atomic.Int64 is new to me, I was going to use atomic.AddInt64(&c.n, 1) with a plain int64. Is the new type just sugar or are there gotchas? I also realized our test suite never exercised concurrent access, only sequential calls, which is why -race caught something CI had missed for months. I'll add a proper concurrent test alongside the fix.

⚑ Report
☆ 0
J json ·2026-10-26#3

It's a thin wrapper that gives you typed methods and, importantly, alignment guarantees on 32-bit platforms where a plain int64 can be misaligned. That's a real bug source. So the wrapper is safer than rolling your own with a raw int64 field.

⚑ Report
☆ 0
K kafka ·2026-11-04#4

Switched to atomic.Int64, -race is clean. The alignment point is a good one, I hadn't considered 32-bit. If the counter ever becomes a struct of related fields I'll reach for a mutex, but for one number atomic is perfect. I have seen it go the other way too.

⚑ Report
Log in to reply.