Skip to content

Commit

Permalink
utils: fix potential goroutine deadlock
Browse files Browse the repository at this point in the history
  • Loading branch information
egonelbre committed Oct 3, 2022
1 parent f526337 commit 13588e6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
8 changes: 7 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/gogo/protobuf/proto"
"golang.org/x/sync/errgroup"

"github.com/jtolio/eventkit/pb"
"github.com/jtolio/eventkit/utils"
Expand Down Expand Up @@ -156,7 +157,12 @@ func (c *UDPClient) Run(ctx context.Context) {
c.init()

ticker := utils.NewJitteredTicker(c.FlushInterval)
defer ticker.Stop()
var background errgroup.Group
defer func() { _ = background.Wait() }()
background.Go(func() error {
ticker.Run(ctx)
return nil
})

p := c.newOutgoingPacket()

Expand Down
20 changes: 9 additions & 11 deletions utils/jitter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"context"
"math/rand"
"sync"
"time"
Expand All @@ -14,35 +15,32 @@ type JitteredTicker struct {
}

func NewJitteredTicker(interval time.Duration) *JitteredTicker {
t := &JitteredTicker{
return &JitteredTicker{
C: make(chan struct{}, 1),
interval: interval,
closed: make(chan struct{}),
}
go t.tick()
return t
}

func (t *JitteredTicker) tick() {
func (t *JitteredTicker) Run(ctx context.Context) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
timer := time.NewTimer(Jitter(r, t.interval))
defer timer.Stop()

for {
select {
case <-t.closed:
case <-ctx.Done():
return
case <-timer.C:
t.C <- struct{}{}
select {
case t.C <- struct{}{}:
case <-ctx.Done():
return
}
timer.Reset(Jitter(r, t.interval))
}
}
}

func (t *JitteredTicker) Stop() {
t.closeOnce.Do(func() { close(t.closed) })
}

func Jitter(r *rand.Rand, t time.Duration) time.Duration {
nanos := r.NormFloat64()*float64(t/4) + float64(t)
if nanos <= 0 {
Expand Down

0 comments on commit 13588e6

Please sign in to comment.