Skip to content

Commit c3d0b96

Browse files
committed
add: arithmetic utilities
1 parent 424fad4 commit c3d0b96

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

Makefile

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
COUNT := $(if $(COUNT),$(COUNT),1)
2+
3+
all:
4+
@echo "Usage:"
5+
@echo " - make tests: run all tests with race detection"
6+
@echo " - make bench count=<number>: run all benches with given count"
7+
8+
tests:
9+
go test -race -cover -coverprofile=cover.test -v .
10+
go tool cover -html=cover.test -o cover.html
11+
12+
bench:
13+
go test -bench=. -benchmem -count=$(COUNT)

arithmetic.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package lockfree
2+
3+
import (
4+
"math"
5+
"sync/atomic"
6+
"unsafe"
7+
)
8+
9+
// AddFloat64 add delta to given address atomically
10+
func AddFloat64(addr *float64, delta float64) (new float64) {
11+
var old float64
12+
for {
13+
old = math.Float64frombits(atomic.LoadUint64((*uint64)(unsafe.Pointer(addr))))
14+
if atomic.CompareAndSwapUint64((*uint64)(unsafe.Pointer(addr)),
15+
math.Float64bits(old), math.Float64bits(old+delta)) {
16+
break
17+
}
18+
}
19+
return
20+
}

arithmetic_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package lockfree_test
2+
3+
import (
4+
"sync"
5+
"testing"
6+
7+
"github.com/changkun/lockfree"
8+
)
9+
10+
func TestAddFloat64(t *testing.T) {
11+
vs := []float64{}
12+
for i := 1; i <= 10; i++ {
13+
vs = append(vs, float64(i))
14+
}
15+
16+
var sum float64
17+
wg := sync.WaitGroup{}
18+
wg.Add(10)
19+
for _, v := range vs {
20+
lv := v
21+
go func() {
22+
lockfree.AddFloat64(&sum, lv)
23+
wg.Done()
24+
}()
25+
}
26+
wg.Wait()
27+
28+
if sum != float64(55) {
29+
t.Fatalf("AddFloat64 wrong, expected 55, got %v", sum)
30+
}
31+
}

0 commit comments

Comments
 (0)