I want to minimize the lock held on a map of items that can be individually locked as soon as the relevant item has been retrieved.
That lead me to believe that
var Mymap struct {
sync.Mutex
m map[string]*Somestruct
}
type Somestruct struct {
sync.Mutex
Someval string
}
could be used like this:
Mymap.Lock()
if val, ok := Mymap.m.[needle]; ok {
Mymap.m.[needle].Lock()
Mymap.Unlock()
// do something to this entry
Mymap.m.[needle].Unlock()
}
Mymap.Unlock()
…but as I understand Unlock()
on an already Unlock
ed is not a no-op:
panic: sync: unlock of unlocked mutex
As per https://groups.google.com/forum/#!topic/Golang-Nuts/GeHbpo6AtTc I see that there is no way to check that it is actually Unlock
ed.
Should I just keep the "Lock" state somewhere or is there a better way of doing it than this:
var unlocked bool
Mymap.Lock()
if val, ok := Mymap.m.[needle]; ok {
Mymap.m.[needle].Lock()
Mymap.Unlock()
unlocked := true
// do something to this entry
Mymap.m.[needle].Unlock()
}
if !unlocked {
Mymap.Unlock()
}