The analyzer has detected a write to a shared variable that is performed under a read lock on sync.RWMutex.RLock. The read lock can be held by multiple goroutines at the same time, so it does not protect against concurrent writes. The write under RLock leads to a race condition.
The rule applies in HTTP handlers and in goroutines, where code runs concurrently.
The example:
var (
cacheMu sync.RWMutex
cache = map[string]string{}
)
func storeHandler(w http.ResponseWriter, r *http.Request) {
key := r.URL.Query().Get("key")
value := r.URL.Query().Get("value")
cacheMu.RLock()
defer cacheMu.RUnlock()
cache[key] = value
}
The write code in cache is protected by the read lock. Multiple requests can capture the RLock simultaneously and write to the map at the same time. This may cause the program to crash with the error fatal error: concurrent map writes.
Typically, this error occurs when:
sync.Mutex type and its sync.Mutex.Lock method are replaced with sync.RWMutex and sync.RWMutex.RLock, respectively.The fixed example:
func storeHandler(w http.ResponseWriter, r *http.Request) {
key := r.URL.Query().Get("key")
value := r.URL.Query().Get("value")
cacheMu.Lock()
defer cacheMu.Unlock()
cache[key] = value
}
This diagnostic rule is classified as:
Was this page helpful?