sync.Map低层工作原理详解
生活随笔
收集整理的这篇文章主要介绍了
sync.Map低层工作原理详解
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
sync.Map低层工作原理详解
目录
1. 为什么需要sync.Map?适合什么场景?
2. sync.Map内部实现基本原理及结构体分析
1. sync.Map结构体
3. sync.Map低层工作原理
1. Store处理过程
// Store sets the value for a key. func (m *Map) Store(key, value interface{}) {read, _ := m.read.Load().(readOnly) // 获取read表if e, ok := read.m[key]; ok && e.tryStore(&value) { // 如果read表中能找到对应key,尝试插入read表对应的key中return}m.mu.Lock()read, _ = m.read.Load().(readOnly) // 对m加锁,重新获取read表,避免虚假报告if e, ok := read.m[key]; ok { // 在read表能查询到,但标记为expunged,则dirty表现创建entry,再存入数据到dirty表if e.unexpungeLocked() {// The entry was previously expunged, which implies that there is a// non-nil dirty map and this entry is not in it.m.dirty[key] = e}e.storeLocked(&value)} else if e, ok := m.dirty[key]; ok { // read表不存在对应key,则判断dirty表是否存在,存在则进行store操作e.storeLocked(&value)} else {if !read.amended { // 如果// We're adding the first new key to the dirty map.// Make sure it is allocated and mark the read-only map as incomplete.m.dirtyLocked()m.read.Store(readOnly{m: read.m, amended: true})}m.dirty[key] = newEntry(value)}m.mu.Unlock() }func (e *entry) tryStore(i *interface{}) bool {for {p := atomic.LoadPointer(&e.p)if p == expunged {return false}if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) {return true}} }用上图的例子,比方说一直频繁调用Load(key4),那么sync.Map就会更换read表
2. Load获取过程
总结
以上是生活随笔为你收集整理的sync.Map低层工作原理详解的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: concurrent map使用
- 下一篇: Janus流媒体服务器框架分析