随机数与并发

• 如果对随机数的数值本身敏感，那么应该在每次程序启动时，使用时间戳初始化随机数
• 在高并发环境下，无脑用随机数，性能很差

伪随机数

package main

import (
"fmt"
"math/rand"
)

func main() {
fmt.Println(rand.Int())
for i := 0; i < 3; i++ {
func(i int) {
rng := rand.New(rand.NewSource(1))
fmt.Println(i, rng.Int())
fmt.Println(i, rng.Int())
fmt.Println(i, rng.Int())
}(i)
}
}

5577006791947779410
0 5577006791947779410
0 8674665223082153551
0 6129484611666145821
1 5577006791947779410
1 8674665223082153551
1 6129484611666145821
2 5577006791947779410
2 8674665223082153551
2 6129484611666145821


#include <stdint.h>

struct xorshift32_state {
uint32_t a;
};

/* The state word must be initialized to non-zero */
uint32_t xorshift32(struct xorshift32_state *state)
{
/* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
uint32_t x = state->a;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
return state->a = x;
}

struct xorshift64_state {
uint64_t a;
};

uint64_t xorshift64(struct xorshift64_state *state)
{
uint64_t x = state->a;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
return state->a = x;
}

struct xorshift128_state {
uint32_t a, b, c, d;
};

/* The state array must be initialized to not be all zero */
uint32_t xorshift128(struct xorshift128_state *state)
{
/* Algorithm "xor128" from p. 5 of Marsaglia, "Xorshift RNGs" */
uint32_t t = state->d;

uint32_t const s = state->a;
state->d = state->c;
state->c = state->b;
state->b = s;

t ^= t << 11;
t ^= t >> 8;
return state->a = t ^ s ^ (s >> 19);
}


Go 随机数实现思路

Go 的 math/rand 包实现了一套伪随机算法，其思路如下

高性能随机数

goos: linux
goarch: amd64
pkg: temp
cpu: Intel(R) Core(TM) i7-6600U CPU @ 2.60GHz
BenchmarkRandom-4                      4         348095650 ns/op
BenchmarkRandomPool-4                  4         303406350 ns/op
BenchmarkFastRand-4                    4         256881850 ns/op
PASS
ok      temp    7.931s