Skip to content

Commit

Permalink
Use goroutine-safe version of rand.Source
Browse files Browse the repository at this point in the history
Signed-off-by: Alexander Morozov <lk4d4@docker.com>
  • Loading branch information
LK4D4 committed May 19, 2015
1 parent 0cc5da0 commit d866125
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 6 deletions.
5 changes: 3 additions & 2 deletions pkg/namesgenerator/names-generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package namesgenerator
import (
"fmt"
"math/rand"
"time"

"github.com/docker/docker/pkg/random"
)

var (
Expand Down Expand Up @@ -309,7 +310,7 @@ var (
"yonath",
}

rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
rnd = rand.New(random.NewSource())
)

func GetRandomName(retry int) string {
Expand Down
34 changes: 34 additions & 0 deletions pkg/random/random.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package random

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

// copypaste from standard math/rand
type lockedSource struct {
lk sync.Mutex
src rand.Source
}

func (r *lockedSource) Int63() (n int64) {
r.lk.Lock()
n = r.src.Int63()
r.lk.Unlock()
return
}

func (r *lockedSource) Seed(seed int64) {
r.lk.Lock()
r.src.Seed(seed)
r.lk.Unlock()
}

// NewSource returns math/rand.Source safe for concurrent use and initialized
// with current unix-nano timestamp
func NewSource() rand.Source {
return &lockedSource{
src: rand.NewSource(time.Now().UnixNano()),
}
}
22 changes: 22 additions & 0 deletions pkg/random/random_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package random

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

// for go test -v -race
func TestConcurrency(t *testing.T) {
rnd := rand.New(NewSource())
var wg sync.WaitGroup

for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
rnd.Int63()
wg.Done()
}()
}
wg.Wait()
}
9 changes: 5 additions & 4 deletions pkg/stringutils/stringutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ package stringutils

import (
"bytes"
mathrand "math/rand"
"math/rand"
"strings"
"time"

"github.com/docker/docker/pkg/random"
)

// Generate alpha only random stirng with length n
func GenerateRandomAlphaOnlyString(n int) string {
// make a really long string
letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]byte, n)
r := mathrand.New(mathrand.NewSource(time.Now().UTC().UnixNano()))
r := rand.New(random.NewSource())
for i := range b {
b[i] = letters[r.Intn(len(letters))]
}
Expand All @@ -26,7 +27,7 @@ func GenerateRandomAsciiString(n int) string {
"~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` "
res := make([]byte, n)
for i := 0; i < n; i++ {
res[i] = chars[mathrand.Intn(len(chars))]
res[i] = chars[rand.Intn(len(chars))]
}
return string(res)
}
Expand Down

0 comments on commit d866125

Please sign in to comment.