-
Notifications
You must be signed in to change notification settings - Fork 593
Description
博客中描述的ConcurrentMap使用分段式锁,把key 分散到固定数量的 shard shard 是有锁保护的 map, 当 shard 进行 rehash 时会阻塞shard内的读写(重点是读写都阻塞),但不会对其他 shard 造成影响。
在博客的讲解中使用的是读锁针对Get方法进行操作,如下:
func (dict *ConcurrentDict) Get(key string) (val interface{}, exists bool) {
if dict == nil {
panic("dict is nil")
}
hashCode := fnv32(key)
index := dict.spread(hashCode)
shard := dict.getShard(index)
shard.mutex.RLock()
defer shard.mutex.RUnlock()
val, exists = shard.m[key]
return
}
但是在您的项目源码中为什么使用的是互斥方式?
func (dict *ConcurrentDict) Get(key string) (val interface{}, exists bool) {
if dict == nil {
panic("dict is nil")
}
hashCode := fnv32(key)
index := dict.spread(hashCode)
s := dict.getShard(index)
s.mutex.Lock() // 对分片加读锁
defer s.mutex.Unlock() // 读锁结束时解锁
val, exists = s.m[key]
return
}