Use goroutine-safe version of rand.Source

Signed-off-by: Alexander Morozov <lk4d4@docker.com>
This commit is contained in:
Alexander Morozov 2015-05-19 12:32:40 -07:00
parent 31232249f7
commit 66d8f1a5ea
4 changed files with 64 additions and 6 deletions

34
random/random.go Normal file
View file

@ -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()),
}
}