Concurrent writes to a map
Description
Writing to a map from multiple goroutines is not concurrency safe. This can lead to a race condition where the map is modified by one goroutine while another goroutine is iterating over it, resulting in unpredictable behavior.
Examples
Insecure Code
go
var m map[string]int
func main() {
m = make(map[string]int)
go func() {
m["key"] = 1
}()
m["key"] = 2
}Secure Code
go
var m map[string]int
var mu sync.Mutex
func main() {
m = make(map[string]int)
go func() {
mu.Lock()
m["key"] = 1
mu.Unlock()
}()
mu.Lock()
m["key"] = 2
mu.Unlock()
}Remediation
Use a mutex to synchronize access to the map, or use a concurrency-safe map implementation.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0273 |
| Category | Concurrency |
| Severity | HIGH |
| CWE | CWE-362 |
| Confidence | MEDIUM |
| Impact | MEDIUM |
| Likelihood | HIGH |
| Exploitability | EASY |
| Tags | race condition, concurrency |
| OWASP | N/A |