I wanted to know if there is a way to lock only an index in a map during concurrent read/write. I am pretty new to Golang and parallelism sorry if the answer is obvious.
func Check(a, b []string) map[string]int {
var res = make(map[string]int)
go func() {
for _, v := range a {
res[v]++
}
}()
go func() {
for _, v := range b {
res[v]++
}
}()
return res
}
Eventually this piece of code is going to panic due to concurrent map Read/Write. So we should add mutex to lock the map.
var m sync.Mutex
go func() {
for _, v := range a {
m.Lock()
res[v]++
m.Unlock()
}
}()
go func() {
for _, v := range b {
m.Lock()
res[v]++
m.Unlock()
}
}()
But from my understanding m.lock()
will lock my whole map? Isn't this too much overhead by locking everything? This bugged me as i thought this piece of code may not be faster than running linearly. Can I possibly lock only the map at map["some key"]
, so that my second goroutine can still write in map["some other key"]
?