Skip to content

Commit

Permalink
Update randx to fix race conditions (#433)
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislas-m committed Aug 28, 2019
1 parent a5b28c0 commit 27cf9ff
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 14 deletions.
2 changes: 0 additions & 2 deletions fix/auto_timestamps_off_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,8 @@ func Test_AutoTimestampsOff(t *testing.T) {
cleaned := re.ReplaceAllString(expected, "")
cleanedPatched := re.ReplaceAllString(patched, "")


rr.Equal(cleaned, cleanedPatched)


})
return nil
})
Expand Down
20 changes: 20 additions & 0 deletions internal/randx/randx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,29 @@ package randx

import (
"math/rand"
"sync"
"time"
)

func init() {
rand.Seed(time.Now().UnixNano())
}

type safeSrc struct {
src rand.Source
moot sync.Mutex
}

func (s *safeSrc) Int63() int64 {
s.moot.Lock()
n := s.src.Int63()
s.moot.Unlock()
return n
}

func newSafeSrc(s rand.Source) *safeSrc {
return &safeSrc{
src: s,
moot: sync.Mutex{},
}
}
3 changes: 2 additions & 1 deletion internal/randx/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ const (
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)

var src = rand.NewSource(time.Now().UnixNano())
var src = newSafeSrc(rand.NewSource(time.Now().UnixNano()))

// String generates a random string with the given length.
func String(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
Expand Down
16 changes: 16 additions & 0 deletions internal/randx/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package randx

import (
"math/rand"
"sync"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -16,3 +17,18 @@ func Test_String(t *testing.T) {
r.Len(String(5), 5)
r.Len(String(50), 50)
}

func Test_String_Parallel(t *testing.T) {
wg := sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
id := String(30)
if len(id) != 30 {
t.FailNow()
}
wg.Done()
}()
}
wg.Wait()
}
22 changes: 11 additions & 11 deletions packrd/packed-packr.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 27cf9ff

Please sign in to comment.