atomicfloat64.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package syncx
  2. import (
  3. "math"
  4. "sync/atomic"
  5. )
  6. // An AtomicFloat64 is an implementation of atomic float64.
  7. type AtomicFloat64 uint64
  8. // NewAtomicFloat64 returns an AtomicFloat64.
  9. func NewAtomicFloat64() *AtomicFloat64 {
  10. return new(AtomicFloat64)
  11. }
  12. // ForAtomicFloat64 returns an AtomicFloat64 with given val.
  13. func ForAtomicFloat64(val float64) *AtomicFloat64 {
  14. f := NewAtomicFloat64()
  15. f.Set(val)
  16. return f
  17. }
  18. // Add adds val to current value.
  19. func (f *AtomicFloat64) Add(val float64) float64 {
  20. for {
  21. old := f.Load()
  22. nv := old + val
  23. if f.CompareAndSwap(old, nv) {
  24. return nv
  25. }
  26. }
  27. }
  28. // CompareAndSwap compares current value with old, if equals, set the value to val.
  29. func (f *AtomicFloat64) CompareAndSwap(old, val float64) bool {
  30. return atomic.CompareAndSwapUint64((*uint64)(f), math.Float64bits(old), math.Float64bits(val))
  31. }
  32. // Load loads the current value.
  33. func (f *AtomicFloat64) Load() float64 {
  34. return math.Float64frombits(atomic.LoadUint64((*uint64)(f)))
  35. }
  36. // Set sets the current value to val.
  37. func (f *AtomicFloat64) Set(val float64) {
  38. atomic.StoreUint64((*uint64)(f), math.Float64bits(val))
  39. }