Why Your Go Worker Pool Still Races After a Mutex on the Results
You ran go test -race, it flagged the results slice, you wrapped the append in a mutex, and the detector is still unhappy. The mutex is not broken. It protects exactly one thing, the moment of appending, and the race is somewhere else.
Here is the usual starting point, with the fix already applied:
type Result struct {
Name string
Body []byte
}
func collect(ctx context.Context, names []string) []Result {
var (
mu sync.Mutex
out []Result
wg sync.WaitGroup
)
for _, n := range names {
wg.Add(1)
go func() {
defer wg.Done()
r := fetch(n)
mu.Lock()
out = append(out, r)
mu.Unlock()
}()
}
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-done:
case <-ctx.Done():
}
return out
}
Looks tidy. It has at least two races in it. Let's find them.
Race one: the reader never took the lock
A mutex only works if every access takes it, reads included. The final return out does not.
When the context is cancelled, select falls through while workers are still running. The function reads out (the slice header: pointer, length, capacity) at the same moment a worker rewrites it inside its locked append. One side holds the lock, the other does not, so the lock does nothing.
Worse, the caller now holds a slice whose backing array a worker may still be writing to. Even if you lock to read the header, the caller is looking at shared memory with no synchronisation after that point.
- If you must return early, lock, copy the slice (
slices.Clone), unlock, and return the copy. - Better: do not return early with partial results unless you have decided that is a feature.
- If you only ever read after
wg.Wait(), the read is safe without the lock, becauseWaitestablishes the ordering. The timeout path is what broke it.
Race two: the mutex guards the header, not what it points to
Suppose fetch reuses a buffer to avoid allocating, which is a very natural optimisation in a pool:
func worker(jobs <-chan string, mu *sync.Mutex, out *[]Result, wg *sync.WaitGroup) {
defer wg.Done()
buf := make([]byte, 64*1024)
for n := range jobs {
k := read(n, buf)
mu.Lock()
*out = append(*out, Result{Name: n, Body: buf[:k]})
mu.Unlock()
}
}
The append is locked. But Body points into buf, and on the next job this worker overwrites buf while someone is reading the earlier result. That is a data race on the bytes, and also a plain logic bug: every result from this worker ends up showing the last job's data.
The race detector reports it on the byte access, nowhere near your mutex, which is why people conclude the mutex "doesn't work". Fix it by copying (bytes.Clone(buf[:k])) or by giving each result its own allocation.
Quick detour: why the detector only sometimes catches this
The -race flag does not prove absence. It watches the accesses that actually happened in that run and reports conflicting ones that lack a happens-before edge. If your test finishes jobs in a lucky order, or the pool is tiny, you get a clean pass.
So run the test with -count=50 and a larger input than your fixture. Races like the timeout one above need the cancel to land mid-flight, so test that path deliberately with a short context and slow fake work.
Race three: you were sharing a variable, not a value
The first example only works as written because the loop variable n is per-iteration. Since Go 1.22, each iteration gets its own copy (when the module's go line is 1.22 or later). On older language versions every goroutine captured the same n, and the loop wrote to it while workers read it. A mutex on out was never going to help.
Check the go directive in go.mod, not just the toolchain you are running. An old directive keeps the old semantics even on a new compiler.
The version with no mutex at all
If you know how many results you will have, you do not need to share the slice. Allocate it up front and let each worker own one slot:
func collect(names []string) []Result {
out := make([]Result, len(names))
var wg sync.WaitGroup
for i, n := range names {
wg.Add(1)
go func() {
defer wg.Done()
out[i] = fetch(n)
}()
}
wg.Wait()
return out
}
Hang on, why is that not a race? Several goroutines write to the same slice. The answer is that out[0] and out[1] are distinct memory locations, and the Go memory model treats writes to different locations as independent. Nobody touches the slice header after make, so nothing conflicts.
The read afterwards is safe because wg.Done happens before the return of wg.Wait. That is the happens-before edge the earlier version threw away on its timeout path.
A bonus: results come back in input order, which the append version never guaranteed. Tests stop being flaky for that reason too.
When you cannot pre-size
For streams of unknown length, send results over a channel and let one goroutine own the slice. Workers send, the collector appends, and nothing is shared. Remember the lesson from race two, though: send values or freshly allocated data, never slices into a buffer you intend to reuse.
The rule that covers all three: a lock protects the memory you take it around, and nothing it merely points to. When the detector complains after you added one, look at who touches the data without the lock before you look at the lock.