mirror of
https://github.com/TeaOSLab/EdgeNode.git
synced 2026-01-02 03:56:36 +08:00
优化代码
This commit is contained in:
@@ -24,11 +24,19 @@ func NewPiece[T any](maxItems int) *Piece[T] {
|
||||
}
|
||||
|
||||
func (this *Piece[T]) Add(key uint64, item *Item[T]) (ok bool) {
|
||||
this.locker.Lock()
|
||||
this.locker.RLock()
|
||||
if this.maxItems > 0 && len(this.m) >= this.maxItems {
|
||||
this.locker.Unlock()
|
||||
this.locker.RUnlock()
|
||||
return
|
||||
}
|
||||
this.locker.RUnlock()
|
||||
|
||||
this.locker.Lock()
|
||||
oldItem, exists := this.m[key]
|
||||
if exists && oldItem.expiredAt == item.expiredAt {
|
||||
this.locker.Unlock()
|
||||
return true
|
||||
}
|
||||
this.m[key] = item
|
||||
this.locker.Unlock()
|
||||
|
||||
|
||||
@@ -18,6 +18,16 @@ func TestPiece_Add(t *testing.T) {
|
||||
t.Log(piece.Read(1))
|
||||
}
|
||||
|
||||
func TestPiece_Add_Same(t *testing.T) {
|
||||
piece := NewPiece[int](10)
|
||||
piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
|
||||
piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
|
||||
for key, item := range piece.m {
|
||||
t.Log(key, item.Value)
|
||||
}
|
||||
t.Log(piece.Read(1))
|
||||
}
|
||||
|
||||
func TestPiece_MaxItems(t *testing.T) {
|
||||
piece := NewPiece[int](10)
|
||||
for i := 0; i < 1000; i++ {
|
||||
|
||||
Reference in New Issue
Block a user