rand.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3. // of this software and associated documentation files (the "Software"), to deal
  4. // in the Software without restriction, including without limitation the rights
  5. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6. // copies of the Software, and to permit persons to whom the Software is
  7. // furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in
  10. // all copies or substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. // THE SOFTWARE.
  19. package utils
  20. import (
  21. "math/rand"
  22. "sync"
  23. )
  24. // lockedSource allows a random number generator to be used by multiple goroutines concurrently.
  25. // The code is very similar to math/rand.lockedSource, which is unfortunately not exposed.
  26. type lockedSource struct {
  27. mut sync.Mutex
  28. src rand.Source
  29. }
  30. // NewRand returns a rand.Rand that is threadsafe.
  31. func NewRand(seed int64) *rand.Rand {
  32. return rand.New(&lockedSource{src: rand.NewSource(seed)})
  33. }
  34. func (r *lockedSource) Int63() (n int64) {
  35. r.mut.Lock()
  36. n = r.src.Int63()
  37. r.mut.Unlock()
  38. return
  39. }
  40. // Seed implements Seed() of Source
  41. func (r *lockedSource) Seed(seed int64) {
  42. r.mut.Lock()
  43. r.src.Seed(seed)
  44. r.mut.Unlock()
  45. }