this is a fatal error: concurrent map read and map write demo code:
package main
var Map = make(map[int]int)
func main() {
for i := 0; i < 100000; i++ {
go updateMap()
go readMap(i)
}
}
func readMap(key int) int {
return Map[key]
}
func updateMap() {
for j := 0; j < 1000; j++ {
Map[j] = j
}
}
I don't use the lock or sync.Map, just use tmp var to replace global map, it will not panic, codes like this:
package main
var Map = make(map[int]int)
func main() {
for i := 0; i < 100000; i++ {
go updateMap()
go readMap(i)
}
}
func readMap(key int) int {
return Map[key]
}
func updateMap() {
tmp := map[int]int{}
for j := 0; j < 1000; j++ {
tmp[j] = j
}
Map = tmp
}
Is there any problem with this way to update the global map?