Skip to content

Commit

Permalink
moving_filter: fix data race with cache result (#6080)
Browse files Browse the repository at this point in the history
ref #5798, close #6069

Signed-off-by: lhy1024 <admin@liudos.us>

Co-authored-by: Ti Chi Robot <ti-community-prow-bot@tidb.io>
  • Loading branch information
lhy1024 and ti-chi-bot committed Mar 3, 2023
1 parent 6fa2bc9 commit d85a0e4
Showing 1 changed file with 17 additions and 28 deletions.
45 changes: 17 additions & 28 deletions pkg/movingaverage/median_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,58 +23,48 @@ type MedianFilter struct {
// It is not thread safe to read and write records at the same time.
// If there are concurrent read and write, the read may get an old value.
// And we should avoid concurrent write.
records []float64
size uint64
count uint64
isUpdated bool
result float64
records []float64
size uint64
count uint64
result float64
}

// NewMedianFilter returns a MedianFilter.
func NewMedianFilter(size int) *MedianFilter {
return &MedianFilter{
records: make([]float64, size),
size: uint64(size),
isUpdated: false,
result: 0,
records: make([]float64, size),
size: uint64(size),
result: 0,
}
}

// Add adds a data point.
func (r *MedianFilter) Add(n float64) {
r.records[r.count%r.size] = n
r.count++
r.isUpdated = true
}

// Get returns the median of the data set.
func (r *MedianFilter) Get() float64 {
if !r.isUpdated {
return r.result
}
if r.count == 0 {
return 0
}
records := r.records
if r.count < r.size {
records = r.records[:r.count]
}
r.result = pie.Median(records)
r.isUpdated = false
}

// Get returns the median of the data set.
func (r *MedianFilter) Get() float64 {
return r.result
}

// Reset cleans the data set.
func (r *MedianFilter) Reset() {
r.count = 0
r.isUpdated = true
r.result = 0
}

// Set = Reset + Add.
func (r *MedianFilter) Set(n float64) {
r.records[0] = n
r.count = 1
r.isUpdated = true
r.result = n
}

// GetInstantaneous returns the value just added.
Expand All @@ -87,10 +77,9 @@ func (r *MedianFilter) Clone() *MedianFilter {
records := make([]float64, len(r.records))
copy(records, r.records)
return &MedianFilter{
records: records,
size: r.size,
count: r.count,
isUpdated: r.isUpdated,
result: r.result,
records: records,
size: r.size,
count: r.count,
result: r.result,
}
}

0 comments on commit d85a0e4

Please sign in to comment.