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流媒体服务器框架分析