Skip to content

Commit

Permalink
Ugh, rand.Int32 not thread safe after rand.NewSource
Browse files Browse the repository at this point in the history
  • Loading branch information
wiggin77 committed Jun 8, 2022
1 parent 8b4c140 commit 64d1857
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,42 @@ package main
import (
"math/rand"
"net/http"
"sync"
"time"

"github.com/mattermost/mattermost-server/v6/model"
)

var rnd *rand.Rand
var mux sync.Mutex

func init() {
s1 := rand.NewSource(time.Now().UnixNano())
rnd = rand.New(s1)
}

func pickRandomString(arr []string) string {
mux.Lock()
defer mux.Unlock()

return arr[rnd.Intn(len(arr))]
}

func pickRandomInt(min int, max int) int {
if min > max {
return max
}

mux.Lock()
defer mux.Unlock()

return rnd.Intn(max-min) + min
}

func shouldDoIt(probability float32) bool {
mux.Lock()
defer mux.Unlock()

return rnd.Float32() <= probability
}

Expand All @@ -46,6 +58,9 @@ func randomDuration(avgDurationMillis int64, variance float32) int64 {
return avgDurationMillis
}

mux.Lock()
defer mux.Unlock()

delta := int64(float32(avgDurationMillis) * variance)
return avgDurationMillis + rnd.Int63n(delta) - rnd.Int63n(delta)
}
Expand Down

0 comments on commit 64d1857

Please sign in to comment.