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 11, 2024
1 parent 780ca9e commit 6e0d2c8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
2 changes: 1 addition & 1 deletion collection/zset/skiplist.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
Expand Down
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
22 changes: 22 additions & 0 deletions collection/zset/zset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"fmt"
"math/rand"
"sort"
"strconv"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -493,6 +495,26 @@ 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(float64(i), strconv.Itoa(i))
}
const G = 10
wg := sync.WaitGroup{}
for i := 0; i < G; i++ {
wg.Add(1)
go func() {
defer wg.Done()
start := fastrand.Intn(N / 2)
stop := N/2 + start
z.RemoveRangeByRank(start, stop)
}()
}
wg.Wait()
}

func TestFloat64SetRemoveRangeByScore(t *testing.T) {
const N = 1000
z := NewFloat64()
Expand Down

0 comments on commit 6e0d2c8

Please sign in to comment.