﻿# V8042\. Writing to a shared variable under a read lock may lead to a data race\. The read lock does not protect against concurrent writes\. Consider using the 'sync\.RWMutex\.Lock' method instead\.

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:

```cpp
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:

* the record is written based on the read code;
* the [`sync.Mutex`](https://pkg.go.dev/sync#Mutex) type and its [`sync.Mutex.Lock`](https://pkg.go.dev/sync#Mutex.Lock) method are replaced with [`sync.RWMutex`](https://pkg.go.dev/sync#RWMutex) and [`sync.RWMutex.RLock`](https://pkg.go.dev/sync#RWMutex.RLock), respectively\.

The fixed example:

```cpp
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
}
```