我想尽量减少在检索到相关项目后可以单独锁定的项目地图上的锁定。
这让我相信
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()
// do something to this entry
Mymap.m.[needle].Unlock()
}
Mymap.Unlock()
...但据我了解Unlock()
已经Unlock
编辑的内容不是无操作:
panic: sync: unlock of unlocked mutex
根据https://groups.google.com/forum/#!topic/Golang-Nuts/GeHbpo6AtTc,我发现没有办法检查它是否真的Unlock
。
我应该在某个地方保持“锁定”状态还是有更好的方法来做到这一点:
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()
}
答案 0 :(得分:2)
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()
}