Skip to content

Commit 10865a5

Browse files
committed
Move rand.Rand and it's mutex into a single struct
1 parent f9f9928 commit 10865a5

1 file changed

Lines changed: 22 additions & 19 deletions

File tree

pkg/random/random.go

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@ var (
2525
"order", "payment", "customer", "product", "stock", "inventory",
2626
"shipping", "billing", "checkout", "cart", "search", "analytics"}
2727

28-
rnd *rand.Rand
29-
randMtx = sync.Mutex{}
28+
// rnd contains rand.Rand instance protected by a mutex
29+
rnd = struct {
30+
sync.Mutex
31+
*rand.Rand
32+
}{}
3033
)
3134

3235
func init() {
@@ -35,24 +38,24 @@ func init() {
3538
if err != nil {
3639
panic(err)
3740
}
38-
rnd = rand.New(rand.NewChaCha8(seed))
41+
rnd.Rand = rand.New(rand.NewChaCha8(seed))
3942
}
4043

4144
func Float32() float32 {
42-
randMtx.Lock()
43-
defer randMtx.Unlock()
45+
rnd.Lock()
46+
defer rnd.Unlock()
4447
return rnd.Float32()
4548
}
4649

4750
func IntN(n int) int {
48-
randMtx.Lock()
49-
defer randMtx.Unlock()
51+
rnd.Lock()
52+
defer rnd.Unlock()
5053
return rnd.IntN(n)
5154
}
5255

5356
func SelectElement[T any](elements []T) T {
54-
randMtx.Lock()
55-
defer randMtx.Unlock()
57+
rnd.Lock()
58+
defer rnd.Unlock()
5659
return elements[rnd.IntN(len(elements))]
5760
}
5861

@@ -69,22 +72,22 @@ func K6String(n int) string {
6972
}
7073

7174
func IntBetween(min, max int) int {
72-
randMtx.Lock()
73-
defer randMtx.Unlock()
75+
rnd.Lock()
76+
defer rnd.Unlock()
7477
n := rnd.IntN(max - min)
7578
return min + n
7679
}
7780

7881
func Duration(min, max time.Duration) time.Duration {
79-
randMtx.Lock()
80-
defer randMtx.Unlock()
82+
rnd.Lock()
83+
defer rnd.Unlock()
8184
n := rnd.Int64N(int64(max) - int64(min))
8285
return min + time.Duration(n)
8386
}
8487

8588
func IPAddr() string {
86-
randMtx.Lock()
87-
defer randMtx.Unlock()
89+
rnd.Lock()
90+
defer rnd.Unlock()
8891
return fmt.Sprintf("192.168.%d.%d", rnd.IntN(255), rnd.IntN(255))
8992
}
9093

@@ -137,8 +140,8 @@ func OperationForResource(resource string) string {
137140
}
138141

139142
func TraceID() pcommon.TraceID {
140-
randMtx.Lock()
141-
defer randMtx.Unlock()
143+
rnd.Lock()
144+
defer rnd.Unlock()
142145

143146
var b [16]byte
144147
binary.BigEndian.PutUint64(b[:8], rnd.Uint64())
@@ -147,8 +150,8 @@ func TraceID() pcommon.TraceID {
147150
}
148151

149152
func SpanID() pcommon.SpanID {
150-
randMtx.Lock()
151-
defer randMtx.Unlock()
153+
rnd.Lock()
154+
defer rnd.Unlock()
152155

153156
var b [8]byte
154157
binary.BigEndian.PutUint64(b[:], rnd.Uint64())

0 commit comments

Comments
 (0)