Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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