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 unlocked 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 unlocked.

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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -