go-zero/core/syncx/atomicfloat64.go

48 lines
1.1 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"math"
"sync/atomic"
)
2021-02-28 16:16:22 +08:00
// An AtomicFloat64 is an implementation of atomic float64.
2020-07-26 17:09:05 +08:00
type AtomicFloat64 uint64
2021-02-28 16:16:22 +08:00
// NewAtomicFloat64 returns an AtomicFloat64.
2020-07-26 17:09:05 +08:00
func NewAtomicFloat64() *AtomicFloat64 {
return new(AtomicFloat64)
}
2021-02-28 16:16:22 +08:00
// ForAtomicFloat64 returns an AtomicFloat64 with given val.
2020-07-26 17:09:05 +08:00
func ForAtomicFloat64(val float64) *AtomicFloat64 {
f := NewAtomicFloat64()
f.Set(val)
return f
}
2021-02-28 16:16:22 +08:00
// Add adds val to current value.
2020-07-26 17:09:05 +08:00
func (f *AtomicFloat64) Add(val float64) float64 {
for {
old := f.Load()
nv := old + val
if f.CompareAndSwap(old, nv) {
return nv
}
}
}
2021-02-28 16:16:22 +08:00
// CompareAndSwap compares current value with old, if equals, set the value to val.
2020-07-26 17:09:05 +08:00
func (f *AtomicFloat64) CompareAndSwap(old, val float64) bool {
return atomic.CompareAndSwapUint64((*uint64)(f), math.Float64bits(old), math.Float64bits(val))
}
2021-02-28 16:16:22 +08:00
// Load loads the current value.
2020-07-26 17:09:05 +08:00
func (f *AtomicFloat64) Load() float64 {
return math.Float64frombits(atomic.LoadUint64((*uint64)(f)))
}
2021-02-28 16:16:22 +08:00
// Set sets the current value to val.
2020-07-26 17:09:05 +08:00
func (f *AtomicFloat64) Set(val float64) {
atomic.StoreUint64((*uint64)(f), math.Float64bits(val))
}