Created
February 9, 2022 23:33
-
-
Save tiwo/d08ac4bf1e1a67f2cfb31dd1372325c0 to your computer and use it in GitHub Desktop.
Golang: fatal error: concurrent map writes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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