英文:
Minimize lock held on map — and instead lock on individual item asap
问题
我想要最小化对一个可以单独锁定的项目映射的锁定时间,一旦相关项目被检索出来就可以立即进行锁定。
这让我相信可以像这样使用:
var Mymap struct {
sync.Mutex
m map[string]*Somestruct
}
type Somestruct struct {
sync.Mutex
Someval string
}
Mymap.Lock()
if val, ok := Mymap.m[needle]; ok {
Mymap.m[needle].Lock()
Mymap.Unlock()
// 对该条目进行操作
Mymap.m[needle].Unlock()
}
Mymap.Unlock()
但是,据我了解,对已经解锁的互斥锁调用Unlock()
并不是一个空操作:
panic: sync: unlock of unlocked mutex
根据https://groups.google.com/forum/#!topic/Golang-Nuts/GeHbpo6AtTc,我了解到没有办法检查互斥锁是否已经解锁。
我应该只是将"Lock"状态保存在某个地方,还是有比这个更好的方法:
var unlocked bool
Mymap.Lock()
if val, ok := Mymap.m[needle]; ok {
Mymap.m[needle].Lock()
Mymap.Unlock()
unlocked := true
// 对该条目进行操作
Mymap.m[needle].Unlock()
}
if !unlocked {
Mymap.Unlock()
}
英文:
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()
}
答案1
得分: 2
Mymap.Lock()
如果 val, ok := Mymap.m.[needle]; ok {
Mymap.m.[needle].Lock()
Mymap.Unlock()
// 对该条目进行操作
Mymap.m.[needle].Unlock()
} else {
Mymap.Unlock()
}
英文:
Mymap.Lock()
if val, ok := Mymap.m.[needle]; ok {
Mymap.m.[needle].Lock()
Mymap.Unlock()
// do something to this entry
Mymap.m.[needle].Unlock()
} else {
Mymap.Unlock()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论