sync.Map低层工作原理详解
生活随笔
收集整理的這篇文章主要介紹了
sync.Map低层工作原理详解
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
sync.Map低層工作原理詳解
目錄
1. 為什么需要sync.Map?適合什么場(chǎng)景?
2. sync.Map內(nèi)部實(shí)現(xiàn)基本原理及結(jié)構(gòu)體分析
1. sync.Map結(jié)構(gòu)體
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表中能找到對(duì)應(yīng)key,嘗試插入read表對(duì)應(yīng)的key中return}m.mu.Lock()read, _ = m.read.Load().(readOnly) // 對(duì)m加鎖,重新獲取read表,避免虛假報(bào)告if e, ok := read.m[key]; ok { // 在read表能查詢到,但標(biāo)記為expunged,則dirty表現(xiàn)創(chuàng)建entry,再存入數(shù)據(jù)到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表不存在對(duì)應(yīng)key,則判斷dirty表是否存在,存在則進(jìn)行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}} }用上圖的例子,比方說一直頻繁調(diào)用Load(key4),那么sync.Map就會(huì)更換read表
2. Load獲取過程
總結(jié)
以上是生活随笔為你收集整理的sync.Map低层工作原理详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: concurrent map使用
- 下一篇: C/C++学习之路_六: 指针