<分区>
关于管理资源集合:
- 可通过全局列表(例如 HashMap )按名称访问
- 从多个线程同时访问
- 引用计数(Golang 缺少“弱引用”;参见
https://groups.google.com/forum/#!topic/golang-nuts/PYWxjT2v6ps)
例子:
var theList tMap // global
// in thread A, B, C etc
aThing := theList.ref("aThing") // if exists then refcount++, else insert
// use aThing
theList.unref("aThing") // refcount--, if 0 then remove
编辑:我希望为此找到推荐的模式,但没有找到任何结果。所以我想到了这个:
type tMap struct {
set map[string]*tMapSet
updt sync.RWMutex
}
type tMapSet struct {
...
refcount int32
}
func (o *tMap) ref(iId string) *tMapSet {
o.updt.RLock()
aSet := o.set[iId]
if aSet != nil {
atomic.AddInt32(&aSet.refcount, 1)
}
o.updt.RUnlock()
if aSet == nil {
o.updt.Lock()
if aTemp := o.set[iId]; aTemp != nil {
aSet = aTemp
aSet.refcount++
} else {
aSet = &tMapSet{refcount:1}
o.set[iId] = aSet
}
o.updt.Unlock()
}
return aSet
}
func (o *tMap) unref(iId string) {
o.updt.RLock()
aSet := o.set[iId]
aN := atomic.AddInt32(&aSet.refcount, -1) // crash if set[iId] not found
o.updt.RUnlock()
if aN == 0 {
o.updt.Lock()
if aSet.refcount == 0 {
delete(o.set, iId)
}
o.updt.Unlock()
}
}
改进上述内容的清晰度或简洁性的建议?