The content of this website is only deployed under the domain
𝙨𝙘𝙤𝙩𝙩𝙮𝙚𝙪𝙣𝙜.𝙩𝙤𝙥(scottyeung[dot]top). Any other domain sites are unauthorized
illegal mirrors.
typeMapstruct{muMutex// 一个原子变量,里面包括一个 map 以及表示 dirty 是否存在 read 当中没有的 entry 的布尔值
// 一般不需要带锁读写
readatomic.Value// readOnly
// 需要带锁读写
dirtymap[any]*entry// 记录 read 当中查询不到需要到 dirty 查询的次数
// 当 misses 达到一定次数时,会将 dirty 整个复制到 read 当中
missesint}// readOnly is an immutable struct stored atomically in the Map.read field.
typereadOnlystruct{mmap[any]*entryamendedbool// true if the dirty map contains some key not in m.
}// expunged is an arbitrary pointer that marks entries which have been deleted
// from the dirty map.
varexpunged=unsafe.Pointer(new(any))
func(m*Map)LoadAndDelete(keyany)(valueany,loadedbool){read,_:=m.read.Load().(readOnly)e,ok:=read.m[key]if!ok&&read.amended{// 如果 read 中不存在且 dirty 中可能存在
m.mu.Lock()read,_=m.read.Load().(readOnly)e,ok=read.m[key]if!ok&&read.amended{e,ok=m.dirty[key]delete(m.dirty,key)// Regardless of whether the entry was present, record a miss: this key
// will take the slow path until the dirty map is promoted to the read
// map.
m.missLocked()// 删除时的查询也需要记录 misses
}m.mu.Unlock()}ifok{returne.delete()}returnnil,false}func(e*entry)delete()(valueany,okbool){for{p:=atomic.LoadPointer(&e.p)ifp==nil||p==expunged{returnnil,false}ifatomic.CompareAndSwapPointer(&e.p,p,nil){// 把 entry 变成空指针
return*(*any)(p),true}}}
预览: