
并发安全 map,上一篇讲解了go 源码自带的 sync.Map{} 的源码实现;本篇文章主要是根据 github.com/orcaman/concurrent-map 中的代码实现,然后进行了相关代码的重构 github.com/libranwmq/cmap,后续需要使用并发安全 map 的童鞋,欢迎使用新的仓库,记得别忘了 star 一下。
这里说明下,为什么我想重构这个这个代码仓。这里的主要原因是,原仓库的代码基本不怎么维护了,我之前提的 issuse 也基本无人问津,并且通过这次重构,对于之前童鞋提出的问题,会在本仓库通过 PR 的方式进行迭代修复,这里也欢迎大家对新的仓库进行优化和问题修复,我会持续跟进本仓库相关问题进展。
(这里只对 cmap 仓库的源码进行解析)

type ConcurrentMapInterface[K Stringer, V any] interface {
Count() int
GetSlotNum() int
IsEmpty() bool
GetSlot(key K) *ConcurrentMapSlotted[K, V]
Set(key K, value V)
SetIfAbsent(key K, value V) bool
MSet(data map[K]V)
Upsert(key K, value V, cb UpsertCb[K, V]) V
Get(key K) (V, bool)
Pop(key K) (v V, ok bool)
Has(key K) bool
Remove(key K)
RemoveCb(key K, cb RemoveCb[K, V]) bool
Iter() <-chan Tuple[K, V]
IterCb(key K, v V, cb IterCb[K, V])
Items() map[K]V
Keys() []K
Tuples() []Tuple[K, V]
Clear()
UnmarshalJSON(b []byte) error
MarshalJSON() ([]byte, error)
}type SlotingFunc[K Stringer] func(key K) uint32
type concurrentMap[K Stringer, V any] struct {
_ nocopy.NoCopy
slotNum int
sloting SlotingFunc[K]
slots []*ConcurrentMapSlotted[K, V]
}concurrentMap:实际并发存储的 map 结构体
type ConcurrentMapSlotted[K Stringer, V any] struct {
items map[K]V
sync.RWMutex
}创建 concurrentMap 实例:
New[K Stringer, V any](opts ...ConcurrentMapOption[K, V]) ConcurrentMapInterface[K, V]type Stringer interface {
fmt.Stringer
comparable
}String() string {}type String string
type Integer int
type Integer32 int32原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。