Skip to content

Commit

Permalink
Implement Add/Sub for Float64 (#17)
Browse files Browse the repository at this point in the history
Signed-off-by: Anton Tiurin <[email protected]>
  • Loading branch information
noxiouz authored and prashantv committed Dec 15, 2016
1 parent 74ca5ec commit 3b8db5e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
16 changes: 16 additions & 0 deletions atomic.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,22 @@ func (f *Float64) Store(s float64) {
atomic.StoreUint64(&f.v, math.Float64bits(s))
}

// Add atomically adds to the wrapped float64 and returns the new value.
func (f *Float64) Add(s float64) float64 {
for {
old := f.Load()
new := old + s
if f.CAS(old, new) {
return new
}
}
}

// Sub atomically subtracts from the wrapped float64 and returns the new value.
func (f *Float64) Sub(s float64) float64 {
return f.Add(-s)
}

// CAS is an atomic compare-and-swap.
func (f *Float64) CAS(old, new float64) bool {
return atomic.CompareAndSwapUint64(&f.v, math.Float64bits(old), math.Float64bits(new))
Expand Down
2 changes: 2 additions & 0 deletions atomic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,6 @@ func TestFloat64(t *testing.T) {

atom.Store(42.0)
require.Equal(t, float64(42.0), atom.Load(), "Store didn't set the correct value.")
require.Equal(t, float64(42.5), atom.Add(0.5), "Add didn't work.")
require.Equal(t, float64(42.0), atom.Sub(0.5), "Sub didn't work.")
}
2 changes: 2 additions & 0 deletions stress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ func TestStressFloat64(t *testing.T) {
runStress(func() {
atom.Load()
atom.CAS(1.0, 0.1)
atom.Add(1.1)
atom.Sub(0.2)
atom.Store(1.0)
})
}
Expand Down

0 comments on commit 3b8db5e

Please sign in to comment.