Skip to content

Instantly share code, notes, and snippets.

@tiwo
Created February 9, 2022 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiwo/d08ac4bf1e1a67f2cfb31dd1372325c0 to your computer and use it in GitHub Desktop.
Save tiwo/d08ac4bf1e1a67f2cfb31dd1372325c0 to your computer and use it in GitHub Desktop.
Golang: fatal error: concurrent map writes
// provoke a crash by cuncurrently writing to the same map from different goroutines
package main
import (
"fmt"
"math/rand"
"sync"
)
func manipulate(wait *sync.WaitGroup, m map[int]int) {
defer wait.Done()
for i := 0; i < 10000; i++ {
key := rand.Intn(100)
value := rand.Intn(99999)
m[key] = value
}
}
func main() {
var wait sync.WaitGroup
m := make(map[int]int)
for i := 0; i < 5; i++ {
wait.Add(1)
go manipulate(&wait, m)
}
wait.Wait()
fmt.Printf("%#v\n", m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment