The analyzer has detected writing to a shared variable from a goroutine without synchronization. A race condition occurs when multiple goroutines access the same variable at the same time and at least one of the accesses is a write operation. Such program behavior is unpredictable.
The example:
func countHandler(w http.ResponseWriter, r *http.Request) {
counter := 0
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter++
}()
}
wg.Wait()
fmt.Fprintf(w, "count: %d", counter)
}
In the example, five gorutins increment the same counter variable. Calling wg.Wait() only ensures that the value will be read once all goroutines have finished, but they are not synchronized with one another.
The counter++ operation is not atomic: it consists of reading, incrementing, and writing the value. Two gorutins can read the same value and write the same result, so some of the increments are lost, and the final value may end up being less than 5.
The race consequences depend on the variable type. For example, concurrent writes to map can cause the program to crash with the fatal error: concurrent map writes message.
There are two options to fix the code.
Option N1. Declare the counter as atomic (atomic.Int32):
func countHandler(w http.ResponseWriter, r *http.Request) {
var counter atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Add(1)
}()
}
wg.Wait()
fmt.Fprintf(w, "count: %d", counter)
}
Option 2. Use sync.Mutex:
func countHandler(w http.ResponseWriter, r *http.Request) {
var mu sync.Mutex
counter := 0
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
counter++
mu.Unlock()
}()
}
wg.Wait()
fmt.Fprintf(w, "count: %d", counter)
}
This diagnostic rule is classified as: