File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -3,7 +3,8 @@ package namesgenerator
33import (
44 "fmt"
55 "math/rand"
6- "time"
6+
7+ "github.com/docker/docker/pkg/random"
78)
89
910var (
@@ -309,7 +310,7 @@ var (
309310 "yonath" ,
310311 }
311312
312- rnd = rand .New (rand .NewSource (time . Now (). UnixNano () ))
313+ rnd = rand .New (random .NewSource ())
313314)
314315
315316func GetRandomName (retry int ) string {
Original file line number Diff line number Diff line change 1+ package random
2+
3+ import (
4+ "math/rand"
5+ "sync"
6+ "time"
7+ )
8+
9+ // copypaste from standard math/rand
10+ type lockedSource struct {
11+ lk sync.Mutex
12+ src rand.Source
13+ }
14+
15+ func (r * lockedSource ) Int63 () (n int64 ) {
16+ r .lk .Lock ()
17+ n = r .src .Int63 ()
18+ r .lk .Unlock ()
19+ return
20+ }
21+
22+ func (r * lockedSource ) Seed (seed int64 ) {
23+ r .lk .Lock ()
24+ r .src .Seed (seed )
25+ r .lk .Unlock ()
26+ }
27+
28+ // NewSource returns math/rand.Source safe for concurrent use and initialized
29+ // with current unix-nano timestamp
30+ func NewSource () rand.Source {
31+ return & lockedSource {
32+ src : rand .NewSource (time .Now ().UnixNano ()),
33+ }
34+ }
Original file line number Diff line number Diff line change 1+ package random
2+
3+ import (
4+ "math/rand"
5+ "sync"
6+ "testing"
7+ )
8+
9+ // for go test -v -race
10+ func TestConcurrency (t * testing.T ) {
11+ rnd := rand .New (NewSource ())
12+ var wg sync.WaitGroup
13+
14+ for i := 0 ; i < 10 ; i ++ {
15+ wg .Add (1 )
16+ go func () {
17+ rnd .Int63 ()
18+ wg .Done ()
19+ }()
20+ }
21+ wg .Wait ()
22+ }
Original file line number Diff line number Diff line change @@ -2,17 +2,18 @@ package stringutils
22
33import (
44 "bytes"
5- mathrand "math/rand"
5+ "math/rand"
66 "strings"
7- "time"
7+
8+ "github.com/docker/docker/pkg/random"
89)
910
1011// Generate alpha only random stirng with length n
1112func GenerateRandomAlphaOnlyString (n int ) string {
1213 // make a really long string
1314 letters := []byte ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" )
1415 b := make ([]byte , n )
15- r := mathrand .New (mathrand .NewSource (time . Now (). UTC (). UnixNano () ))
16+ r := rand .New (random .NewSource ())
1617 for i := range b {
1718 b [i ] = letters [r .Intn (len (letters ))]
1819 }
@@ -26,7 +27,7 @@ func GenerateRandomAsciiString(n int) string {
2627 "~!@#$%^&*()-_+={}[]\\ |<,>.?/\" ';:` "
2728 res := make ([]byte , n )
2829 for i := 0 ; i < n ; i ++ {
29- res [i ] = chars [mathrand .Intn (len (chars ))]
30+ res [i ] = chars [rand .Intn (len (chars ))]
3031 }
3132 return string (res )
3233}
You can’t perform that action at this time.
0 commit comments