diff options
author | Roger Peppe <rogpeppe@gmail.com> | 2009-12-09 12:55:19 -0800 |
---|---|---|
committer | Roger Peppe <rogpeppe@gmail.com> | 2009-12-09 12:55:19 -0800 |
commit | e4eb8e849a10a083114e8b1c37b3170cd3ec2e66 (patch) | |
tree | 729a08c23d0bab1ec570feb2d926ba18d14fe2d6 | |
parent | 1cfd640626b449c4978643aa9c28eb7cb32cbbad (diff) | |
download | golang-e4eb8e849a10a083114e8b1c37b3170cd3ec2e66.tar.gz |
Make the operations on the global rng thread safe.
R=r, rsc
CC=golang-dev
http://codereview.appspot.com/168041
Committer: Russ Cox <rsc@golang.org>
-rw-r--r-- | src/pkg/rand/rand.go | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/src/pkg/rand/rand.go b/src/pkg/rand/rand.go index 68e6e2c20..0063e4059 100644 --- a/src/pkg/rand/rand.go +++ b/src/pkg/rand/rand.go @@ -5,6 +5,8 @@ // Package rand implements pseudo-random number generators. package rand +import "sync" + // A Source represents a source of uniformly-distributed // pseudo-random int64 values in the range [0, 1<<63). type Source interface { @@ -91,7 +93,7 @@ func (r *Rand) Perm(n int) []int { * Top-level convenience functions */ -var globalRand = New(NewSource(1)) +var globalRand = New(&lockedSource{src: NewSource(1)}) // Seed uses the provided seed value to initialize the generator to a deterministic state. func Seed(seed int64) { globalRand.Seed(seed) } @@ -148,3 +150,21 @@ func NormFloat64() float64 { return globalRand.NormFloat64() } // sample = ExpFloat64() / desiredRateParameter // func ExpFloat64() float64 { return globalRand.ExpFloat64() } + +type lockedSource struct { + lk sync.Mutex; + src 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(); +} |