Initial commit (code only without large binaries)
This commit is contained in:
46
EdgeNode/internal/utils/sync/counter.go
Normal file
46
EdgeNode/internal/utils/sync/counter.go
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||
|
||||
package syncutils
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type CounterType interface {
|
||||
int32 | int64 | uint32 | uint64
|
||||
}
|
||||
|
||||
type Counter[T CounterType] struct {
|
||||
values *Values[T]
|
||||
}
|
||||
|
||||
func NewCounter[T CounterType]() *Counter[T] {
|
||||
return &Counter[T]{
|
||||
values: NewValues[T](func() T {
|
||||
return 0
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (this *Counter[T]) Add(delta T) {
|
||||
this.values.DoUnsafe(func(value *T) {
|
||||
switch x := any(value).(type) {
|
||||
case *int32:
|
||||
atomic.AddInt32(x, int32(delta))
|
||||
case *int64:
|
||||
atomic.AddInt64(x, int64(delta))
|
||||
case *uint32:
|
||||
atomic.AddUint32(x, uint32(delta))
|
||||
case *uint64:
|
||||
atomic.AddUint64(x, uint64(delta))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (this *Counter[T]) Load() T {
|
||||
var result T
|
||||
this.values.DoUnsafeAll(func(value T) {
|
||||
result += value
|
||||
})
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user