Skip to content

Commit

Permalink
encapsulate mutex lock
Browse files Browse the repository at this point in the history
  • Loading branch information
mbrostami committed Mar 22, 2022
1 parent 4b91dae commit 90369c8
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions consistenthash.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type HashFunc func(data []byte) uint32

// ConsistentHash everything we need for CH
type ConsistentHash struct {
sync.RWMutex
mu sync.RWMutex
hash HashFunc
replicas int // default number of replicas in hash ring (higher number means more posibility for balance equality)
hKeys []uint32 // Sorted
Expand Down Expand Up @@ -61,8 +61,8 @@ func (ch *ConsistentHash) Get(key string) string {
if ch.IsEmpty() {
return ""
}
ch.RLock()
defer ch.RUnlock()
ch.mu.RLock()
defer ch.mu.RUnlock()
hash := ch.hash([]byte(key))

// Binary search for appropriate replica
Expand All @@ -81,8 +81,8 @@ func (ch *ConsistentHash) Remove(key string) bool {
return true
}
replicas := ch.rTable[key]
ch.Lock()
defer ch.Unlock()
ch.mu.Lock()
defer ch.mu.Unlock()
for i := 0; i < replicas; i++ {
hash := ch.hash([]byte(strconv.Itoa(i) + key))
delete(ch.hTable, hash) // delete replica
Expand All @@ -104,8 +104,8 @@ func (ch *ConsistentHash) removeHashKey(hash uint32) {

// add inserts new hash in hash table
func (ch *ConsistentHash) add(key string, replicas int) {
ch.Lock()
defer ch.Unlock()
ch.mu.Lock()
defer ch.mu.Unlock()
for i := 0; i < replicas; i++ {
hash := ch.hash([]byte(strconv.Itoa(i) + key))
ch.hKeys = append(ch.hKeys, hash)
Expand Down

0 comments on commit 90369c8

Please sign in to comment.