Skip to content

Instantly share code, notes, and snippets.

@vizee
Created July 29, 2017 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vizee/cb2f08bb807bc2a5d5f85b1e741799d8 to your computer and use it in GitHub Desktop.
Save vizee/cb2f08bb807bc2a5d5f85b1e741799d8 to your computer and use it in GitHub Desktop.
go thread-safe rand
package mtrnd
import (
"math/rand"
"sync"
"time"
"github.com/vizee/asm/hack"
)
var (
rndmu sync.Mutex
rnds []*rand.Rand
)
func currnd() *rand.Rand {
pid := hack.ProcPin()
if pid >= len(rnds) {
hack.ProcUnpin()
rndmu.Lock()
pid = hack.ProcPin()
if pid >= len(rnds) {
t := make([]*rand.Rand, pid+1)
n := copy(t, rnds)
for i := n; i < len(t); i++ {
t[i] = rand.New(rand.NewSource(time.Now().UnixNano() ^ int64(i)))
}
rnds = t
}
rndmu.Unlock()
}
r := rnds[pid]
hack.ProcUnpin()
return r
}
func Int() int {
return currnd().Int()
}
func Intn(n int) int {
return currnd().Intn(n)
}
func Uint64() uint64 {
return currnd().Uint64()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment