diff options
author | 2022-03-16 09:24:58 -0700 | |
---|---|---|
committer | 2022-03-16 12:24:58 -0400 | |
commit | aa7818e1d342ffbed3588f6bdece621b119debec (patch) | |
tree | d718b6040cfb0f64562fcf8c818598c7ac29e689 /plugin/pkg/rand | |
parent | c3b30cc3ef57393a7f4cab1bf3b6c4124e72a36e (diff) | |
download | coredns-aa7818e1d342ffbed3588f6bdece621b119debec.tar.gz coredns-aa7818e1d342ffbed3588f6bdece621b119debec.tar.zst coredns-aa7818e1d342ffbed3588f6bdece621b119debec.zip |
Update to avoid pseudo-random number (#5225)
* Update to avoid pseudo-random number
This PR update the usage of rand so that non-global seed is used.
Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
* Add concurrency-safe random source
See https://stackoverflow.com/questions/48958886/how-to-create-a-thread-safe-rand-source
Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
Diffstat (limited to 'plugin/pkg/rand')
-rw-r--r-- | plugin/pkg/rand/rand.go | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/plugin/pkg/rand/rand.go b/plugin/pkg/rand/rand.go new file mode 100644 index 000000000..d2b3960b4 --- /dev/null +++ b/plugin/pkg/rand/rand.go @@ -0,0 +1,36 @@ +// Package rand is used for concurrency safe random number generator. +package rand + +import ( + "math/rand" + "sync" +) + +// Rand is used for concurrency safe random number generator. +type Rand struct { + m sync.Mutex + r *rand.Rand +} + +// New returns a new Rand from seed. +func New(seed int64) *Rand { + return &Rand{r: rand.New(rand.NewSource(seed))} +} + +// Int returns a non-negative pseudo-random int from the Source in Rand.r. +func (r *Rand) Int() int { + r.m.Lock() + v := r.r.Int() + r.m.Unlock() + return v +} + +// Perm returns, as a slice of n ints, a pseudo-random permutation of the +// integers in the half-open interval [0,n) from the Source in Rand.r. +func (r *Rand) Perm(n int) []int { + r.m.Lock() + v := r.r.Perm(n) + r.m.Unlock() + return v + +} |