尽量减少对地图的锁定时间,而是尽快对单个项目进行锁定。

huangapple go评论113阅读模式
英文:

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

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()
}

huangapple
  • 本文由 发表于 2017年9月11日 05:27:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/46145728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定