Skip to content

Commit

Permalink
fix: zset remove range by rank lock by read mutex bytedance#234
Browse files Browse the repository at this point in the history
  • Loading branch information
Thoren-byte committed Dec 10, 2024
1 parent 780ca9e commit 8510a88
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions collection/zset/zset.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,8 +382,8 @@ func (z *Float64Set) RevRangeByScoreWithOpt(max, min float64, opt RangeOpt) []Fl
//
// RemoveRangeByRank is the replacement of ZREMRANGEBYRANK command of redis.
func (z *Float64Set) RemoveRangeByRank(start, stop int) []Float64Node {
z.mu.RLock()
defer z.mu.RUnlock()
z.mu.Lock()
defer z.mu.Unlock()

// Convert negative rank to positive.
if start < 0 {
Expand Down
29 changes: 29 additions & 0 deletions collection/zset/zset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"fmt"
"math/rand"
"sort"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -493,6 +494,33 @@ func TestFloat64SetRemoveRangeByRank(t *testing.T) {
assert.Equal(t, N, z.Len()+len(actualNs))
}

func TestFloat64SetRemoveRangeByRankConcurrently(t *testing.T) {
const N = 10000
z := NewFloat64()
for i := 0; i < N; i++ {
z.Add(fastrand.Float64(), fmt.Sprint(i))
}

start, stop := func(a, b int) (int, int) {
if a < b {
return a, b
} else {
return b, a
}
}(fastrand.Intn(N), fastrand.Intn(N))

const G = 10
wg := sync.WaitGroup{}
for i := 0; i < G; i++ {
wg.Add(1)
go func() {
defer wg.Done()
z.RemoveRangeByRank(start, stop)
}()
}
wg.Wait()
}

func TestFloat64SetRemoveRangeByScore(t *testing.T) {
const N = 1000
z := NewFloat64()
Expand Down Expand Up @@ -618,3 +646,4 @@ func TestInterFloat64_Simple(t *testing.T) {
z := InterFloat64(z1, z2, z3)
assert.Zero(t, z.Len())
}

0 comments on commit 8510a88

Please sign in to comment.