go - Minimize lock held on map — and instead lock on individual item asap -
i want minimize lock held on map of items can individually locked relevant item has been retrieved.
that lead me believe
var mymap struct { sync.mutex m map[string]*somestruct } type somestruct struct { sync.mutex someval string }
could used this:
mymap.lock() if val, ok := mymap.m.[needle]; ok { mymap.m.[needle].lock() mymap.unlock() // entry mymap.m.[needle].unlock() } mymap.unlock()
…but understand unlock()
on unlock
ed not no-op:
panic: sync: unlock of unlocked mutex
as per https://groups.google.com/forum/#!topic/golang-nuts/gehbpo6attc see there no way check unlock
ed.
should keep "lock" state somewhere or there better way of doing this:
var unlocked bool mymap.lock() if val, ok := mymap.m.[needle]; ok { mymap.m.[needle].lock() mymap.unlock() unlocked := true // entry mymap.m.[needle].unlock() } if !unlocked { mymap.unlock() }
mymap.lock() if val, ok := mymap.m.[needle]; ok { mymap.m.[needle].lock() mymap.unlock() // entry mymap.m.[needle].unlock() } else { mymap.unlock() }
Comments
Post a Comment