Counting words in goroutines
CountWords splits work across goroutines. Under load the process dies with "fatal error: concurrent map writes". Why?
func CountWords(docs []string) map[string]int { counts := make(map[string]int) var wg sync.WaitGroup for _, doc := range docs { wg.Add(1) go func(d string) { defer wg.Done() for _, w := range strings.Fields(d) { counts[w]++ } }(doc) } wg.Wait() return counts}Show answer
line 9 · Race condition
Go maps are not safe for concurrent writes. Several goroutines update counts at once, which the runtime detects and treats as a fatal error that can't be recovered.
var mu sync.Mutex // ... inside the goroutine: for _, w := range strings.Fields(d) { mu.Lock() counts[w]++ mu.Unlock() }Interview follow-up: Better still: count into a local map per goroutine and merge at the end, so the lock is taken once per document.