Skip to content

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

FieldValue
IDCODE-0273
CategoryConcurrency
SeverityHIGH
CWECWE-362
ConfidenceMEDIUM
ImpactMEDIUM
LikelihoodHIGH
ExploitabilityEASY
Tagsrace condition, concurrency
OWASPN/A

References