atomicfloat64.go 771 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package syncx
  2. import (
  3. "math"
  4. "sync/atomic"
  5. )
  6. type AtomicFloat64 uint64
  7. func NewAtomicFloat64() *AtomicFloat64 {
  8. return new(AtomicFloat64)
  9. }
  10. func ForAtomicFloat64(val float64) *AtomicFloat64 {
  11. f := NewAtomicFloat64()
  12. f.Set(val)
  13. return f
  14. }
  15. func (f *AtomicFloat64) Add(val float64) float64 {
  16. for {
  17. old := f.Load()
  18. nv := old + val
  19. if f.CompareAndSwap(old, nv) {
  20. return nv
  21. }
  22. }
  23. }
  24. func (f *AtomicFloat64) CompareAndSwap(old, val float64) bool {
  25. return atomic.CompareAndSwapUint64((*uint64)(f), math.Float64bits(old), math.Float64bits(val))
  26. }
  27. func (f *AtomicFloat64) Load() float64 {
  28. return math.Float64frombits(atomic.LoadUint64((*uint64)(f)))
  29. }
  30. func (f *AtomicFloat64) Set(val float64) {
  31. atomic.StoreUint64((*uint64)(f), math.Float64bits(val))
  32. }