Skip to content

Commit

Permalink
cmd/multiping: protect result slices with mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
dmke committed Feb 21, 2018
1 parent 8283be2 commit f3fb400
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions cmd/multiping/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"

Expand All @@ -18,6 +19,7 @@ type stats struct {
received int
lost int
results []time.Duration // ring buffer, index = .received
mtx sync.RWMutex
}

type unit struct {
Expand Down Expand Up @@ -116,15 +118,20 @@ func (u *unit) ping(pinger *ping.Pinger) {
}

func (s *stats) addResult(rtt time.Duration, err error) {
s.mtx.Lock()
if err == nil {
s.results[s.received%len(s.results)] = rtt
s.received++
} else {
s.lost++
}
s.mtx.Unlock()
}

func (s *stats) compute() (pktSent int, pktLoss float64, last, best, worst, mean, stddev time.Duration) {
s.mtx.RLock()
defer s.mtx.RUnlock()

if s.received == 0 {
if s.lost > 0 {
pktLoss = 1.0
Expand Down

0 comments on commit f3fb400

Please sign in to comment.