Skip to content

Commit a690c23

Browse files
committed
Fixed thread safety issues
1 parent 20b26a5 commit a690c23

File tree

1 file changed

+98
-2
lines changed

1 file changed

+98
-2
lines changed

Random.go

Lines changed: 98 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,104 @@ package u
22

33
import (
44
"math/rand"
5+
"sync"
56
"time"
67
)
78

8-
var GlobalRand1 = rand.New(rand.NewSource(int64(time.Now().Nanosecond())))
9-
var GlobalRand2 = rand.New(rand.NewSource(int64(time.Now().Unix())))
9+
var GlobalRand1 = NewRand(rand.NewSource(int64(time.Now().Nanosecond())))
10+
var GlobalRand2 = NewRand(rand.NewSource(int64(time.Now().Nanosecond())))
11+
12+
func NewRand(source rand.Source) *Rand {
13+
return &Rand{
14+
goRand: rand.New(source),
15+
}
16+
}
17+
18+
type Rand struct {
19+
goRand *rand.Rand
20+
lock sync.Mutex
21+
}
22+
23+
func (r *Rand) Seed(seed int64) {
24+
r.lock.Lock()
25+
defer r.lock.Unlock()
26+
r.goRand.Seed(seed)
27+
}
28+
29+
func (r *Rand) Int63() int64 {
30+
r.lock.Lock()
31+
defer r.lock.Unlock()
32+
return r.goRand.Int63()
33+
}
34+
35+
func (r *Rand) Uint32() uint32 {
36+
r.lock.Lock()
37+
defer r.lock.Unlock()
38+
return r.goRand.Uint32()
39+
}
40+
41+
func (r *Rand) Uint64() uint64 {
42+
r.lock.Lock()
43+
defer r.lock.Unlock()
44+
return r.goRand.Uint64()
45+
}
46+
47+
func (r *Rand) Int31() int32 {
48+
r.lock.Lock()
49+
defer r.lock.Unlock()
50+
return r.goRand.Int31()
51+
}
52+
53+
func (r *Rand) Int() int {
54+
r.lock.Lock()
55+
defer r.lock.Unlock()
56+
return r.goRand.Int()
57+
}
58+
59+
func (r *Rand) Int63n(n int64) int64 {
60+
r.lock.Lock()
61+
defer r.lock.Unlock()
62+
return r.goRand.Int63n(n)
63+
}
64+
65+
func (r *Rand) Int31n(n int32) int32 {
66+
r.lock.Lock()
67+
defer r.lock.Unlock()
68+
return r.goRand.Int31n(n)
69+
}
70+
71+
func (r *Rand) Intn(n int) int {
72+
r.lock.Lock()
73+
defer r.lock.Unlock()
74+
return r.goRand.Intn(n)
75+
}
76+
77+
func (r *Rand) Float64() float64 {
78+
r.lock.Lock()
79+
defer r.lock.Unlock()
80+
return r.goRand.Float64()
81+
}
82+
83+
func (r *Rand) Float32() float32 {
84+
r.lock.Lock()
85+
defer r.lock.Unlock()
86+
return r.goRand.Float32()
87+
}
88+
89+
func (r *Rand) Perm(n int) []int {
90+
r.lock.Lock()
91+
defer r.lock.Unlock()
92+
return r.goRand.Perm(n)
93+
}
94+
95+
func (r *Rand) Shuffle(n int, swap func(i, j int)) {
96+
r.lock.Lock()
97+
defer r.lock.Unlock()
98+
r.goRand.Shuffle(n, swap)
99+
}
100+
101+
func (r *Rand) Read(p []byte) (n int, err error) {
102+
r.lock.Lock()
103+
defer r.lock.Unlock()
104+
return r.goRand.Read(p)
105+
}

0 commit comments

Comments
 (0)