Created
July 29, 2017 08:12
-
-
Save vizee/cb2f08bb807bc2a5d5f85b1e741799d8 to your computer and use it in GitHub Desktop.
go thread-safe rand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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