Go 1.19.3 sync.Map原理简析

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

sync.Map解决了map不能并发读写的问题

sync.Map适用于读多写少的场景。其原理是使用两个map(readdirty)进行读写分离但两个map共用底层的entry实体。所以说两个map中key各有一份但value对应的entry只有一份。read map 中存在的有效的值dirty map中也会存在。当读取read map获取不到key的次数到达一定阈值后dirty map会提升为read map。dirty map被再创建时会浅拷贝read map。
本博文源码均来自于 src/sync/map.go

// Map is like a Go map[interface{}]interface{} but is safe for concurrent use
// by multiple goroutines without additional locking or coordination.
// Loads, stores, and deletes run in amortized constant time.
//Map 类似于 Go map[interface{}]interface{}但可以安全地由多个 goroutines 并发使用无需额外的锁定或协调。加载、存储和删除在摊销的常量时间内运行。
// The Map type is specialized. Most code should use a plain Go map instead,
// with separate locking or coordination, for better type safety and to make it
// easier to maintain other invariants along with the map content.
//
//Map类型是专用的。大多数代码应改用纯 Go 映射具有单独的锁定或协调以提高类型安全性并更轻松地维护其他不变量以及映射内容。
// The Map type is optimized for two common use cases: (1) when the entry for a given
// key is only ever written once but read many times, as in caches that only grow,
// or (2) when multiple goroutines read, write, and overwrite entries for disjoint
// sets of keys. In these two cases, use of a Map may significantly reduce lock
// contention compared to a Go map paired with a separate Mutex or RWMutex.
//Map 类型针对两种常见用例进行了优化1 当给定键的条目只写入一次但读取多次时例如在仅增长的缓存中或 2 当多个 goroutine读取、写入和覆盖不相交键集的条目时。在这两种情况下与与单独的互斥或 RWMutex 配对的 Go 映射相比使用 Map 可以显著减少锁争用。

// The zero Map is empty and ready for use. A Map must not be copied after first use.

//零映射为空可供使用。Map在首次使用后不得复制。
// In the terminology of the Go memory model, Map arranges that a write operation
// “synchronizes before” any read operation that observes the effect of the write, where
// read and write operations are defined as follows.
// Load, LoadAndDelete, LoadOrStore are read operations;
// Delete, LoadAndDelete, and Store are write operations;
// and LoadOrStore is a write operation when it returns loaded set to false.
//在 Go 内存模型的术语中Map 安排写入操作在观察写入效果的任何读取操作之前“同步”其中读取和写入操作定义如下。Load、LoadAndDelete、LoadOrStore 是读取操作;删除、加载和删除和存储是写入操作;LoadOrStore 是返回 load set 为 false 时的写入操作。

sync.Map 底层结构

type Map struct {
	mu Mutex

	// read contains the portion of the map's contents that are safe for
	// concurrent access (with or without mu held).
	//
	// The read field itself is always safe to load, but must only be stored with
	// mu held.
	//
	// Entries stored in read may be updated concurrently without mu, but updating
	// a previously-expunged entry requires that the entry be copied to the dirty
	// map and unexpunged with mu held.
	// 读取包含映射内容中可安全并发访问的部分保留或不保留 MU。读取字段本身始终可以安全加载但只能与 mu 一起存储。存储在读取中的条目可以在没有 mu 的情况下同时更新但更新以前删除的条目需要将该条目复制到脏映射中并在保留 mu 的情况下取消删除。
	read atomic.Value // readOnly 原子Value这里用作只读

	// dirty contains the portion of the map's contents that require mu to be
	// held. To ensure that the dirty map can be promoted to the read map quickly,
	// it also includes all of the non-expunged entries in the read map.
	//
	// Expunged entries are not stored in the dirty map. An expunged entry in the
	// clean map must be unexpunged and added to the dirty map before a new value
	// can be stored to it.
	//
	// If the dirty map is nil, the next write to the map will initialize it by
	// making a shallow copy of the clean map, omitting stale entries.
	//dirty 字段包含Map内容中需要保留 MU 的部分。为了确保脏映射可以快速提升为读取映射它还包括读取映射中所有未删除的条目。删除的条目不会存储在脏映射中。清理映射中已清除的条目必须取消删除并添加到脏映射中然后才能将新值存储到脏映射中。如果脏映射为 nil则下次写入映射时将通过创建干净映射的浅拷贝来初始化它省略过时的条目。
	dirty map[any]*entry

	// misses counts the number of loads since the read map was last updated that
	// needed to lock mu to determine whether the key was present.
	//
	// Once enough misses have occurred to cover the cost of copying the dirty
	// map, the dirty map will be promoted to the read map (in the unamended
	// state) and the next store to the map will make a new dirty copy.
	// misses 计算自上次更新读取映射以来需要锁定 MU 以确定密钥是否存在的负载数。一旦发生足够的未命中以支付复制脏映射的成本脏映射将被提升为读取Map处于未修改状态Map的下一个存储将制作新的脏副本。
	misses int
}

Map中有四个字段
mu Mutex保护后续三个字段的并发安全
read atomic.Value作为只读的map使用不会写入
dirty map[any]*entry写入的map
misses int未命中read map的数到达一定值dirty提升为read

readOnly结构

包含了只读map的实例m和amended字段如果该字段为true证明dirty map中有一部分key不在当前m中。

// readOnly is an immutable struct stored atomically in the Map.read field.
type readOnly struct {
	m       map[any]*entry
	amended bool // true if the dirty map contains some key not in m.
}

expunged 表示已删除的状态

excunged是一个任意类型的指针用于标记已删除的条目在dirty map上。

// expunged is an arbitrary pointer that marks entries which have been deleted
// from the dirty map.
var expunged = unsafe.Pointer(new(any))

entry 真正存储数据的实体同一个entry的引用被read 和 dirty 共享

// An entry is a slot in the map corresponding to a particular key.
// 条目是Map中与特定key相对应的槽位
type entry struct {
	// p points to the interface{} value stored for the entry.
	// p指向为条目存储的空接口值
	// If p == nil, the entry has been deleted, and either m.dirty == nil or
	// m.dirty[key] is e.
	//
	// If p == expunged, the entry has been deleted, m.dirty != nil, and the entry
	// is missing from m.dirty.
	//
	// Otherwise, the entry is valid and recorded in m.read.m[key] and, if m.dirty
	// != nil, in m.dirty[key].
	//
	// An entry can be deleted by atomic replacement with nil: when m.dirty is
	// next created, it will atomically replace nil with expunged and leave
	// m.dirty[key] unset.
	//
	// An entry's associated value can be updated by atomic replacement, provided
	// p != expunged. If p == expunged, an entry's associated value can be updated
	// only after first setting m.dirty[key] = e so that lookups using the dirty
	// map find the entry.
	p unsafe.Pointer // *interface{}
}

entry 作为key对应的value。
entry 结构体中有一个字段p其类型为unsafe.Pointer类型其指向一个空接口指针可以保存任何数据。
如果 p 等于 expunged即该实体已经被删除m.dirty != nil, 并且 这个entry将被从dirty中清理。否则该entry有效并记录在m.read.m[key]中如果m.dirty != nil那么也存储在m.dirty中。entry可以通过原子替换为nil来删除当m.dirty为下一次创建时它将原子性地将nil替换为删除并离开m.dirty[key]。
entry的关联值可以通过原子替换来更新前提是 p != expunged。如果 p 等于 expunged则只有在首次设置 m.dirty[key] = e 后才能更新entry的关联值以便使用脏映射的查找找到该条目。

newEntry 根据传入的值创建一个entry

func newEntry(i any) *entry {
	return &entry{p: unsafe.Pointer(&i)}
}

entry.load 从entry加载出其保存的any类型的value和该值是否存在

func (e *entry) load() (value any, ok bool) {
	p := atomic.LoadPointer(&e.p) // 原子加载指针p
	if p == nil || p == expunged { // p 为 空 或 已删除状态
		return nil, false          // 返回 nil,false 代表该entry中无有效的值
	}
	return *(*any)(p), true      // 强转为*any指针后用*解引用返回解引用后的any值和true表示该entry中有有效的值
}

entry.tryStore

// tryStore stores a value if the entry has not been expunged.
// 如果entry没有被删除tryStore保存一个值到其中。
// If the entry is expunged, tryStore returns false and leaves the entry
// unchanged.
// 如果entry已经被删除tryStore 返回false否则用原子操作更新entry的p指针
func (e *entry) tryStore(i *any) bool {
	for { //自旋操作等待时机
		p := atomic.LoadPointer(&e.p) //原子操作加载p指针
		if p == expunged { // p 是已删除状态
			return false
		}
		if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) { //原子操作更新指针
			return true
		}
	}
}

e.unexpungeLocked 确保entry未标记成已删除若标记成已删除则用nil填充

// unexpungeLocked ensures that the entry is not marked as expunged.
//
// If the entry was previously expunged, it must be added to the dirty map
// before m.mu is unlocked.
// 如果之前删除过该entry它将加入到dirty map
func (e *entry) unexpungeLocked() (wasExpunged bool) {
	return atomic.CompareAndSwapPointer(&e.p, expunged, nil)
}

e.storeLocked存储传入值到该entryentry必须是非expunged状态

// storeLocked unconditionally stores a value to the entry.
//
// The entry must be known not to be expunged.
func (e *entry) storeLocked(i *any) {
	atomic.StorePointer(&e.p, unsafe.Pointer(i))
}

e.tryLoadOrStore 尝试加载或存储

// tryLoadOrStore atomically loads or stores a value if the entry is not
// expunged.
//
// If the entry is expunged, tryLoadOrStore leaves the entry unchanged and
// returns with ok==false.
//tryLoadOrStore 以原子方式加载或存储一个值,如果该entry被清除tryLoadOrStore 将保留该entry不变并以 ok==false 返回
func (e *entry) tryLoadOrStore(i any) (actual any, loaded, ok bool) { // 真正的entry是否为被加载出来的值是否有效
	p := atomic.LoadPointer(&e.p) // 加载指针
	if p == expunged { // 判定是否为被删除状态
		return nil, false, false // 返回nilfalsefalse
	}
	if p != nil { // 返回有效的加载出来的entry
		return *(*any)(p), true, true
	}

	// Copy the interface after the first load to make this method more amenable
	// to escape analysis: if we hit the "load" path or the entry is expunged, we
	// shouldn't bother heap-allocating.
	// 在第一次加载后复制接口使此方法更适合逃逸分析如果我们命中“load”路径或entry被删除我们不应该费心分配堆。

    // 尝试存储传入的i 
	ic := i // 赋值传入的i浅拷贝
	for { // 自旋
		if atomic.CompareAndSwapPointer(&e.p, nil, unsafe.Pointer(&ic)) { // 若e.p为nil则尝试更新e.p
			return i, false, true // 返回传入的i非加载值有效
		}
		p = atomic.LoadPointer(&e.p) // 加载指针p
		if p == expunged { // 删除状态
			return nil, false, false
		}
		if p != nil { //非删除状态返回加载出的值及bool变量
			return *(*any)(p), true, true
		}
	}
}

entry.delete 清空entry的值并返回旧值及 是否清空

func (e *entry) delete() (value any, ok bool) {
	for { // 自旋
		p := atomic.LoadPointer(&e.p)
		if p == nil || p == expunged {
			return nil, false
		}
		if atomic.CompareAndSwapPointer(&e.p, p, nil) {
			return *(*any)(p), true
		}
	}
}

e.tryExpungeLocked 尝试将entry的p为nil的entry标记成expunged状态即被删除状态

func (e *entry) tryExpungeLocked() (isExpunged bool) {
	p := atomic.LoadPointer(&e.p)
	for p == nil {
		if atomic.CompareAndSwapPointer(&e.p, nil, expunged) {
			return true
		}
		p = atomic.LoadPointer(&e.p)
	}
	return p == expunged
}

Map.Load 返回Map中key对应的value及该value是否存在

// Load returns the value stored in the map for a key, or nil if no
// value is present.
// The ok result indicates whether value was found in the map.
func (m *Map) Load(key any) (value any, ok bool) {
	read, _ := m.read.Load().(readOnly) // 先原子操作加载read map断言成readOnly类型
	e, ok := read.m[key]                // 获取key对应的value及key是否存在
	if !ok && read.amended {            // 若key不存在并且dirty中有read中没有的key
		m.mu.Lock()                     // 加锁
		// Avoid reporting a spurious miss if m.dirty got promoted while we were
		// blocked on m.mu. (If further loads of the same key will not miss, it's
		// not worth copying the dirty map for this key.)
		read, _ = m.read.Load().(readOnly) // 再次尝试从read map中获取
		e, ok = read.m[key]
		if !ok && read.amended { // 若key不存在并且dirty中有read中没有的key
			e, ok = m.dirty[key] // 尝试去 dirty中去查找
			// 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() //更新未命中数
		}
		m.mu.Unlock() //解锁
	}
	if !ok { // 若值不存在则返回nilfalse
		return nil, false
	}
	return e.load() // 若值存在则去对应的entry中去获取
}

Map.missLocked 更新读取read map的未命中数若该数据小于dirty map的数据个数则返回否则将dirty map 提升为read mapdirty map 清空未命中数重置为0

func (m *Map) missLocked() {
	m.misses++
	if m.misses < len(m.dirty) {
		return
	}
	m.read.Store(readOnly{m: m.dirty})
	m.dirty = nil
	m.misses = 0
}

Map.Store 向sync Map中存储key value

// Store sets the value for a key.
func (m *Map) Store(key, value any) {
	read, _ := m.read.Load().(readOnly) // 如果read map 中存在传入的key则原子操作更新key 对应的value 因为value的底层entry被read map 和 dirty map 共享所以更新操作两个map都可见
	if e, ok := read.m[key]; ok && e.tryStore(&value) {
		return //更新成功则返回
	}

    // 以上尝试不成功则加锁
	m.mu.Lock()
	read, _ = m.read.Load().(readOnly) //获取read map
	if e, ok := read.m[key]; ok { // read map 中有传入的key,获取key对应的entry
		if e.unexpungeLocked() { // entry 已被删除 其p = nil
			// 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 // 则直接将key e放入 dirty map中
		}
		e.storeLocked(&value) // 将value 保存到e中
	} else if e, ok := m.dirty[key]; ok { // 若dirty map 中有该key潜台词 read map中没有该key
		e.storeLocked(&value) // 直接将value 保存到key 对应的entry
	} else { // read map 和 dirty map 中都没有该key
		if !read.amended { // diry map 中 不包含 read map 没有的key 
			// 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() // 获取或重建dirty map
			m.read.Store(readOnly{m: read.m, amended: true}) // 更新read map 的 amended 为true代表dirty map 中有read map 中没有的key
		}
		m.dirty[key] = newEntry(value) // 赋值dirty map key 对应的entry的p指向value
	}
	m.mu.Unlock() // 解锁
}

Map.dirtyLocked 获取或重建dirty map若dirty map非空直接返回为空则浅拷贝read map中的值到dirty map

func (m *Map) dirtyLocked() {
	if m.dirty != nil {
		return
	}

	read, _ := m.read.Load().(readOnly)
	m.dirty = make(map[any]*entry, len(read.m))
	for k, e := range read.m {
		if !e.tryExpungeLocked() { // 只复制未打删除状态标记的e
			m.dirty[k] = e
		}
	}
}

Map.LoadOrStore 加载或存储有key则加载无key则存储

// LoadOrStore returns the existing value for the key if present.
// Otherwise, it stores and returns the given value.
// The loaded result is true if the value was loaded, false if stored.
func (m *Map) LoadOrStore(key, value any) (actual any, loaded bool) {
	// Avoid locking if it's a clean hit.
	read, _ := m.read.Load().(readOnly) // 加载
	if e, ok := read.m[key]; ok {
		actual, loaded, ok := e.tryLoadOrStore(value)
		if ok {
			return actual, loaded
		}
	}

    // 存储
	m.mu.Lock()
	read, _ = m.read.Load().(readOnly) // 二次加载
	if e, ok := read.m[key]; ok { // read map 中有key
		if e.unexpungeLocked() { // 指针为空
			m.dirty[key] = e     // 向dirty map 中存
		}
		actual, loaded, _ = e.tryLoadOrStore(value)
	} else if e, ok := m.dirty[key]; ok { // dirty map 中有key
		actual, loaded, _ = e.tryLoadOrStore(value)
		m.missLocked()
	} else { // 以上二者均无key
		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)
		actual, loaded = value, false
	}
	m.mu.Unlock()

	return actual, loaded
}

Map.LoadAndDelete 加载并删除

// LoadAndDelete deletes the value for a key, returning the previous value if any.
// The loaded result reports whether the key was present.
func (m *Map) LoadAndDelete(key any) (value any, loaded bool) {
	read, _ := m.read.Load().(readOnly) // 加载read map
	e, ok := read.m[key]   // 获取value 及key 是否存在 
	if !ok && read.amended { // 不存在key并且dirty map 中有
		m.mu.Lock() // 加锁
		read, _ = m.read.Load().(readOnly)
		e, ok = read.m[key]
		if !ok && read.amended { // 二次判定
			e, ok = m.dirty[key] // 从dirty map 中删除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() // 更新未命中数
		}
		m.mu.Unlock() // 解锁
	}
	if ok {
		return e.delete() // 清理enrty结构的p
	}
	return nil, false
}

Map.Delete 删除key

// Delete deletes the value for a key.
func (m *Map) Delete(key any) {
	m.LoadAndDelete(key)
}

Map.Range 迭代Map当read的amended为true时提升dirty map 为read map

// Range calls f sequentially for each key and value present in the map.
// If f returns false, range stops the iteration.
//
// Range does not necessarily correspond to any consistent snapshot of the Map's
// contents: no key will be visited more than once, but if the value for any key
// is stored or deleted concurrently (including by f), Range may reflect any
// mapping for that key from any point during the Range call. Range does not
// block other methods on the receiver; even f itself may call any method on m.
//
// Range may be O(N) with the number of elements in the map even if f returns
// false after a constant number of calls.
func (m *Map) Range(f func(key, value any) bool) {
	// We need to be able to iterate over all of the keys that were already
	// present at the start of the call to Range.
	// If read.amended is false, then read.m satisfies that property without
	// requiring us to hold m.mu for a long time.
	read, _ := m.read.Load().(readOnly)
	if read.amended {
		// m.dirty contains keys not in read.m. Fortunately, Range is already O(N)
		// (assuming the caller does not break out early), so a call to Range
		// amortizes an entire copy of the map: we can promote the dirty copy
		// immediately!
		m.mu.Lock()
		read, _ = m.read.Load().(readOnly)
		if read.amended {
			read = readOnly{m: m.dirty}
			m.read.Store(read)
			m.dirty = nil
			m.misses = 0
		}
		m.mu.Unlock()
	}

	for k, e := range read.m {
		v, ok := e.load()
		if !ok {
			continue
		}
		if !f(k, v) { // 回调根据回调的返回值确定是否要继续迭代
			break
		}
	}
}
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: go