I have the following code, and I am having data race. The Round function periodically check runs the function to delete the contents of the map As I read here: Is it safe to remove selected keys from Golang map within a range loop?
Removing the data from map is safe, but I am having data race
package main
import (
"fmt"
"sync"
"time"
)
type City struct {
ID string
}
type Map struct {
sync.RWMutex
Data map[string]City
}
var done = make(chan struct{})
func (m *Map) Round() {
for {
select {
case <-time.After(2 * time.Second):
for i, v := range m.Data {
fmt.Println("-----", v)
delete(m.Data, i)
}
case <-done:
println("bye")
break
}
}
}
func (m *Map) Add(id string, h City) {
m.Lock()
m.Data[id] = h
m.Unlock()
}
func main() {
m := Map{}
m.Data = make(map[string]City)
m.Data["Ottowa"] = City{"Canada"}
m.Data["London"] = City{"GB"}
m.Data["malafya"] = City{"malafya"}
go m.Round()
for i := 0; i < 4; i++ {
go func() {
time.Sleep(2 * time.Second)
go m.Add("uz", City{"CityMakon"})
go m.Add("uzb", City{"CityMakon"})
}()
}
time.Sleep(5 * time.Second)
done <- struct{}{}
}
the output:
----- {Canada}
----- {GB}
----- {malafya}
==================
WARNING: DATA RACE
Write by goroutine 12:
runtime.mapassign1()
/usr/lib/golang/src/runtime/hashmap.go:411 +0x0
main.(*Map).Add()
/home/narkoz/elixir/round.go:37 +0xaa
Previous write by goroutine 6:
runtime.mapdelete()
/usr/lib/golang/src/runtime/hashmap.go:511 +0x0
main.(*Map).Round()
/home/narkoz/elixir/round.go:26 +0x3a9
Goroutine 12 (running) created at:
main.main.func1()
/home/narkoz/elixir/round.go:54 +0x8c
Goroutine 6 (running) created at:
main.main()
/home/narkoz/elixir/round.go:49 +0x2af
==================
----- {CityMakon}
----- {CityMakon}
Found 1 data race(s)
exit status 66
But when I change the value type of the map to int or string, there is not data race.
What solution do you recommend ?