I am a newcomer to the go language. When I execute the code, I get the following error:
fatal error: concurrent map read and map write
func foo() {
var m = map[string]int{"a": 1}
var lock = sync.RWMutex{}
go Read(m, lock)
time.Sleep(1 * time.Second)
go Write(m, lock)
time.Sleep(1 * time.Minute)
}
func main() {
foo()
}
func Read(m map[string]int, lock sync.RWMutex) {
for {
read(m, lock)
}
}
func Write(m map[string]int, lock sync.RWMutex) {
for {
write(m, lock)
}
}
func read(m map[string]int, lock sync.RWMutex) {
lock.RLock()
defer lock.RUnlock()
_ = m["a"]
}
func write(m map[string]int, lock sync.RWMutex) {
lock.Lock()
defer lock.Unlock()
m["b"] = 2
}
anyone can tell me why?
You must pass a pointer to your sync.RWMutex value. Otherwise, you're making copies of the mutex every time you pass it to a new function, so no actual locking happens.
The go vet tool will detect this error for you. You should run go vet (and likely other linters) on all your code, to help catch such common errors. Related reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With