Skip to content

Commit f61d1a1

Browse files
authored
Merge pull request #3 from Layer8Collective/fix-race
fix: race condition
2 parents b37cd15 + 0706c63 commit f61d1a1

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

main.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ import (
66
"net/http"
77
"netexp/netdev"
88
"netexp/pipeline"
9+
"netexp/rcu"
910
"os"
1011
"time"
1112
)
1213

1314
var (
1415
version = "0.3.8"
15-
metrics []byte
16+
metrics rcu.RCU[[]byte]
1617
listen string
1718
getver bool
1819
)
@@ -45,7 +46,7 @@ func serve() {
4546
})
4647

4748
http.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
48-
w.Write(metrics)
49+
w.Write(*metrics.Load())
4950
})
5051

5152
go func() {
@@ -72,7 +73,9 @@ func gather() {
7273
panic(fmt.Errorf("could not get traffic: %w", err))
7374
}
7475

75-
metrics = p.Step(recv, trns)
76+
buf := p.Step(recv, trns)
77+
78+
metrics.Store(&buf)
7679

7780
time.Sleep(time.Second)
7881
}

rcu/rcu.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package rcu
2+
3+
import "sync/atomic"
4+
5+
type RCU[T any] struct {
6+
p atomic.Pointer[T]
7+
}
8+
9+
func (r *RCU[T]) Store(t *T) {
10+
r.p.Store(t)
11+
}
12+
13+
func (r *RCU[T]) Load() *T {
14+
return r.p.Load()
15+
}

0 commit comments

Comments
 (0)